能否在from 之后加 case when 语句?

nevermorewish 2013-05-05 04:03:01
实现如下需求
如果table1的col1字段 值为 1,从test1表中取数据
如果table1的col1字段 值为 2,从test2表中取数据
create  table test1
(
col int
);
insert test1 (col) values(10);
create table test2
(
col int
);
insert test2 (col) values(20);

create table table1
(
col1 int,
col2 int,
col3 int,
col int
);
insert table1 (col1) values(1);

--如果table1的col1字段 值为 1,从test1表中取数据
--如果table1的col1字段 值为 2,从test2表中取数据
declare @tempid int
select @tempid = col1
from table1
-- 下面代码无法使用
-- select * from (case when @tempid = 1 then test1 else test2 end)
...全文
922 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
csdnTimePeriod 2013-05-06
  • 打赏
  • 举报
回复
语法通不过就只好换方法。用if语句吧? if @tempid=1 select * from test1 else select * from test2
Sweet-Tang 2013-05-05
  • 打赏
  • 举报
回复

select * from test1 where @tempid = 1 
union all
select * from test2 where @tempid = 2
唐诗三百首 2013-05-05
  • 打赏
  • 举报
回复
用条件判断或动态SQL实现..

create  table test1(col int)

insert test1(col) values(10)

create  table test2(col int)

insert test2(col) values(20)
 
create  table table1
( col1 int,col2 int,col3 int,col int)

insert table1(col1) values(1)


-- 方法1
declare @tempid int,@tsql varchar(6000)

select @tempid=col1 from table1
select @tsql='select * from '+case @tempid when 1 then 'test1' when 2 then 'test2' end

exec(@tsql)

-- 方法2
declare @tempid int

select @tempid=col1 from table1

if @tempid=1
 select * from test1
else
 select * from test2
 
-- 结果
/*
col
-----------
10

(1 row(s) affected)
*/
szm341 2013-05-05
  • 打赏
  • 举报
回复
不可以,表名如果是动态的话,需要用exec(@sql)动态执行

34,588

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧