如何有条件地将内部联接添加到 select 语句?
我有一个变量,我需要检查它的值是什么,并且我需要根据该值对不同的表进行内部联接。这是我要问的一个例子...
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
更新:我想我应该包括我正在使用通用表表达式,并且我已经尝试使用动态sql,甚至使用 if 语句来调用不同的 CTE,但似乎CTE 不喜欢任何东西,只喜欢简单的 select 语句。
感谢您对我能得到的任何建议。
I have a variable that I need to check to see what the value is and I need to do an inner join to different tables based on what that value is. Here's an example of what I'm asking...
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
UPDATE: I think I should have included that I'm using Common Table Expressions and I've tried using dynamic sql, and even doing if statements to call different CTE's, but it seems that CTE's do not like anything but a simple select statement.
Thanks for any advice I can get on this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种方法是:
One approach is:
将整个查询设为 varchar,然后使用动态执行。
Make your whole query a varchar, then use dynamic execution.