我来自MySQL现在在SQL Server中工作,编写一个存储过程,需要根据Description列中的值在“like”子句中设置一个值。不确定我是否应该声明一个变量(@desc),然后设置它是否有更简单的方法?
的伪代码:
DECLARE @desc varchar(255);
IF [Description] LIKE '%KK%'
SET @desc = 'KDues';
ELSE
SET @desc = 'BDues';
实际查询
SELECT
Description,AmountDue
[...]
WHERE order_date BETWEEN @fiscalYearBeginDate AND @fiscalYearEndDate
AND [Description] LIKE '%'+@desc+'%'
最好的方法是什么?不确定如何在此特定方案中使用IF / ELSE或CASE。感谢
答案 0 :(得分:2)
您可以使用case
声明:
SELECT Description, AmountDue
[...]
WHERE order_date BETWEEN @fiscalYearBeginDate AND @fiscalYearEndDate and
Description like (case when Description LIKE '%KK%' then '%KDues%' else '%BDues%' end)
然而,这很难看。您可以使用逻辑消除case
:
WHERE order_date BETWEEN @fiscalYearBeginDate AND @fiscalYearEndDate and
((Description like '%KK%' and Description like '%KDues%') or
(Description not like '%KK%' and Description like '%BDues%')
)
顺便说一句,MySQL和SQL Server中的这两种形式都是相同的。
答案 1 :(得分:2)
SELECT
case when Description like '%KK%'
then 'KDues'
ELSE
'BDues' end as Description ,AmountDue
[...]
WHERE order_date BETWEEN @fiscalYearBeginDate AND @fiscalYearEndDate