我有一个变量,我需要检查以查看值是什么,我需要根据该值的内部连接到不同的表。这是我要问的一个例子......
Declare @category nvarchar(100)
select *
from tableA a
if (@category = 'all)
begin
inner join tableB b on b.ID = a.ID
end
else if (@category = 'open')
begin
inner join tableC c on c.ID = a.ID
end
更新:我想我应该包括我正在使用Common Table Expressions并且我尝试使用动态sql,甚至做if语句来调用不同的CTE,但似乎CTE不喜欢任何东西而只是简单选择陈述。
感谢您提出任何建议。
答案 0 :(得分:2)
一种方法是:
select *
from tableA a
inner join tableB b on b.ID = a.ID
where @category = 'all'
union all
select *
from tableA a
inner join tableC c on c.ID = a.ID
where @category = 'open'
答案 1 :(得分:0)
使整个查询成为varchar,然后使用动态执行。
declare @sqltorun as varchar(max)
set @sqltorun = 'select * from tableA a '
if(@Category=='a')
@sqltorun = @sqltorun + 'inner join tableB b on b.ID = a.ID '
else
@sqltorun = @sqltorun + 'inner join tableB b on b.ID = a.ID '
sp_executesql @sqltorun