2

是否可以将值传递给存储过程以告诉它是否将 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 子句,而不是从应用程序再次访问数据库?

4

3 回答 3

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 等于 'that' 时才提供成功。

于 2013-05-21T12:51:30.180 回答
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''
于 2013-05-21T12:51:08.627 回答
1
SELECT xyzName
FROM xyz_fields
WHERE (xyzType = 'this')
OR ((xyzType = 'that') AND @status = 1)
OR ((xyzType = 'somethingelse') AND @status2 = 1)

When @status = 1, ((xyzType = 'that') AND @status = 1)returns (xyzType = 'that'), 但是 when @status = 0, ((xyzType = 'that') AND @status = 1)returnfalse并不会影响你的查询。

于 2013-05-21T12:59:19.797 回答