SQL WHERE子句中的IF语句

时间:2013-05-21 12:48:02

标签: sql sql-server sql-server-2008 tsql sql-server-2012

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

我尝试了类似的东西,但它无效:

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子句而不是再次从应用程序中访问数据库?

3 个答案:

答案 0 :(得分:4)

我认为你的意思是这样的:

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

当@status等于1且xyzType等于'that'时,where子句的第二行仅提供成功。

答案 1 :(得分: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) 

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

WHERE  xyzType = 'this' 

应该是

WHERE  xyzType = ''this''

答案 2 :(得分: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并且不会影响您的查询。