[英]Where and if clause in SQL query
在存储过程中,假设我有一个flag ,它可以是0或1
如果为1 ,那么我想select * from table A where name = 'blah'
。
如果为0 ,那么我想select * from table A where name = blah and age = 13
。
有没有一种方法可以将and age = 13
添加到存储过程查询中?
这就是我目前所拥有的。
IF @flag = 1
SELECT * from A where name = 'blah'
ELSE
SELECT * from A where name = 'blah' and age = 13
我想知道查询变得很长的情况,因此在ELSE
情况下复制和粘贴更多类似的代码效率很低。
谢谢。
SELECT * from A
where name = 'blah'
and (@flag = 1 or age = 13)
您还可以使用Case statement
;
Select * from A
Where Name = 'blah' And Age = Case @flag when 1 then Age else 13 end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.