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

求一 SQL语句
我想在查询中根据不同的情况取不同的库表
例如:

 declare @ab varchar(1)
 select @ab= case when bh = '1' then 'table1' else 'table2' 
 
 select bh,mc from @ab
 /*我这么写 执行的时候提示 没有@ab 表*/ 

我的目标就是 当bh 等于 1 则数据就从table1表中获取数据   否则数据都充table2中获取
感觉是不是要写成动态SQL啊  如何写啊

------解决方案--------------------

declare @bh varchar(1000)='1'

declare @ab varchar(1000)
select @ab= case when @bh = '1' then 'table1' else 'table2' end
  
Exec('select bh,mc from '+ @ab)


------解决方案--------------------

declare @ab varchar(10),@tsql varchar(6000)

select @ab=case when bh='1' then 'table1' else 'table2' end
  
select @tsql='select bh,mc from '+@ab

exec(@tsql)