2013-05-21 163 views
2

是否可以将值传递给存储过程以告诉它是否将OR语句附加到SQL SELECT语句?SQL语句中的IF语句WHERE子句

我已经试过像这样,但它是无效的:的

SELECT xyzName 
FROM xyz_fields 
WHERE (xyzType = 'this') UNION ALL 
(if @status=1 OR (xyzType = 'that')) UNION ALL 
(if @status2=1 OR (xyzType = 'somethingelse')) 

有点像在SQL建立WHERE子句,而不是从应用程序再次击中DB?

+0

尝试使用case语句。请发布你的数据和你需要什么输出.. –

+0

你必须更具体...你的查询没有意义,问题也混乱... – Nathan

回答

2

您可以使用动态SQL来做到这一点。

declare @SqlQuery varchar(100) 

Set @SqlQuery = ' SELECT xyzName FROM xyz_fields WHERE xyzType = ''this'' ' 

if(@status=1) 
Set @SqlQuery = @SqlQuery + ' OR xyzType = ''that'' ' 

if(@status2=1) 
Set @SqlQuery = @SqlQuery + ' OR xyzType = ''somethingelse''' 

exec(@SqlQuery) 

查询中的单个qoute通过为另一个qoute加前缀而被转义。 所以在查询

WHERE xyzType = 'this' 

应该

WHERE xyzType = ''this'' 
+0

似乎是这样可能是一个好方法,如果正确,我会放弃并标记为答案。努力+1,谢谢! – Apqu

+0

更新:这似乎工作得很好,非常感谢发布此解决方案。 – Apqu

+0

'很高兴我能帮到' –

4

我想你的意思是这样的:

SELECT xyzName 
FROM xyz_fields 
WHERE (xyzType = 'this') 
OR (@status=1 AND (xyzType = 'that')) 
OR (@status2=1 AND (xyzType = 'somethingelse')) 

的第二行where子句仅传送成功时@status等于1和xyzType等于'那个'。

1
SELECT xyzName 
FROM xyz_fields 
WHERE (xyzType = 'this') 
OR ((xyzType = 'that') AND @status = 1) 
OR ((xyzType = 'somethingelse') AND @status2 = 1) 

@status = 1((xyzType = 'that') AND @status = 1)回报(xyzType = 'that'), 但当@status = 0((xyzType = 'that') AND @status = 1)回报false并不会影响您的查询。