实现如下需求
如果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)

解决方案 »

  1.   

    不可以,表名如果是动态的话,需要用exec(@sql)动态执行
      

  2.   

    用条件判断或动态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' endexec(@tsql)-- 方法2
    declare @tempid intselect @tempid=col1 from table1if @tempid=1
     select * from test1
    else
     select * from test2
     
    -- 结果
    /*
    col
    -----------
    10(1 row(s) affected)
    */
      

  3.   


    select * from test1 where @tempid = 1 
    union all
    select * from test2 where @tempid = 2
      

  4.   

    语法通不过就只好换方法。用if语句吧?
    if @tempid=1
    select * from test1
    else
    select * from test2