日期:2014-05-17  浏览次数:21322 次

能否在from 之后加 case when 语句?
实现如下需求
如果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)

------解决方案--------------------
用条件判断或动态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)
*/