如何在 WHERE 子句中使用 IF ELSE
Posted
技术标签:
【中文标题】如何在 WHERE 子句中使用 IF ELSE【英文标题】:How to use IF ELSE inside WHERE clause 【发布时间】:2014-04-11 07:55:08 【问题描述】:是否可以在 WHERE 子句中使用类似这样的 IF ELSE...
WHERE transactionId like @transactionId
AND transactionType like @transactionType
AND customerId like @customerId
IF(@transactionType='1')
AND qTable.statusId like 'SIGNED'
ELSE
AND rTable.statusId like 'ACTIVE'
【问题讨论】:
SQL: IF clause within WHERE clause的可能重复 【参考方案1】:您不能在WHERE
子句中使用IF ELSE
语句。请改用CASE
:
WHERE transactionId like @transactionId
AND transactionType like @transactionType
AND customerId like @customerId
AND CASE WHEN @transactionType = '1' THEN qTable.statusId like 'SIGNED'
ELSE rTable.statusId like 'ACTIVE' END
【讨论】:
【参考方案2】:WHERE transactionId like @transactionId
AND transactionType like @transactionType
AND customerId like @customerId
AND
((@transactionType='1' AND qTable.statusId like 'SIGNED')
OR
(@transactionType <> '1' AND like 'ACTIVE') )
【讨论】:
【参考方案3】:这是你需要的吗?
WHERE transactionId like @transactionId
AND transactionType like @transactionType
AND customerId like @customerId
AND ((transactionType='1' and qTable.statusId like 'SIGNED') or (transactionType <> '1' and rTable.statusId like 'ACTIVE'))
【讨论】:
以上是关于如何在 WHERE 子句中使用 IF ELSE的主要内容,如果未能解决你的问题,请参考以下文章
SQL Server:IF .. ELSE 中的 Where 子句