错误156严重性15状态1,使用语法CASE WHEN ELSE END

时间:2019-06-15 10:20:42

标签: sql sql-server switch-statement

从存储过程中声明@Keyword时,我有新的WHERE条件。但是当我尝试使用CASE语法时,出现错误“关键字'LIKE'附近的语法不正确。”

我已经在PostgreSQL中尝试了这种CASE语法,但是没有错误。

ALTER PROCEDURE [dbo].[ACC_SEARCH_INVOICE_DATEX]
@projectID  varchar(3),
@FromDate DATETIME,
@Todate DATETIME ,
@Filter varchar(50),
@Keyword varchar(50),
@posted int,

@status integer,
@source varchar(50)
AS

SELECT posted, InvoiceHead.InvoiceID, InvoiceHead.Date AS date, InvoiceHead.UserID, InvoiceHead.CreditTerm, InvoiceHead.DueDate, InvoiceHead.CustomerID, 
Party.Name, InvoiceHead.Total, InvoiceHead.Currency, InvoiceHead.Rate, Subtotal, Discount, Tax, Commision, Bonus, Total, DownPayment, Balance ,
substring(InvoiceID,4,LEN(invoiceid)-11-3) Source, selling, technician, Lock , InvoiceHead.Status

FROM InvoiceHead LEFT OUTER JOIN Party ON InvoiceHead.CustomerID = Party.PartyID  

WHERE 

CASE
 WHEN @Keyword = 'SCP' 
    THEN ((InvoiceHead.InvoiceID LIKE '%' + @Keyword + '%') or (InvoiceHead.InvoiceID LIKE '%SCJ%'))
 WHEN  @Keyword = 'SCNH' 
    THEN ((InvoiceHead.InvoiceID LIKE '%' + @Keyword + '%') or (InvoiceHead.InvoiceID LIKE '%SNJH%'))
 WHEN  @Keyword = 'SCNHL' 
    THEN ((InvoiceHead.InvoiceID LIKE '%' + @Keyword + '%') or (InvoiceHead.InvoiceID LIKE '%SNJHL%'))
 ELSE ((InvoiceHead.InvoiceID LIKE '%' + @Keyword + '%'))
END

ORDER BY   InvoiceHead.InvoiceID

3 个答案:

答案 0 :(得分:0)

您应该重新构造条件:

WHERE 
(CASE
 WHEN @Keyword = 'SCP'   AND ((InvoiceHead.InvoiceID LIKE '%' + @Keyword + '%') or (InvoiceHead.InvoiceID LIKE '%SCJ%'))   THEN 1
 WHEN @Keyword = 'SCNH'  AND ((InvoiceHead.InvoiceID LIKE '%' + @Keyword + '%') or (InvoiceHead.InvoiceID LIKE '%SNJH%'))  THEN 1
 WHEN @Keyword = 'SCNHL' AND ((InvoiceHead.InvoiceID LIKE '%' + @Keyword + '%') or (InvoiceHead.InvoiceID LIKE '%SNJHL%')) THEN 1
 WHEN ((InvoiceHead.InvoiceID LIKE '%' + @Keyword + '%')) THEN 1
END) = 1

答案 1 :(得分:0)

您可以像下面那样使用


WHERE (@Keyword = 'SCP'   AND ((InvoiceHead.InvoiceID LIKE '%' + @Keyword + '%') or (InvoiceHead.InvoiceID LIKE '%SCJ%'))) 
  OR  (@Keyword = 'SCNH' AND ((InvoiceHead.InvoiceID LIKE '%' + @Keyword + '%') or (InvoiceHead.InvoiceID LIKE '%SNJH%')))
  OR  (@Keyword = 'SCNHL' AND ((InvoiceHead.InvoiceID LIKE '%' + @Keyword + '%') or (InvoiceHead.InvoiceID LIKE '%SNJHL%')))

答案 2 :(得分:0)

您可以在没有case的情况下构造此逻辑。我建议以下内容:

WHERE InvoiceHead.InvoiceID LIKE '%' + @Keyword + '%') OR
      (@Keyword = 'SCP' AND InvoiceHead.InvoiceID LIKE '%SCJ%') OR
      (@Keyword = 'SCNH' AND InvoiceHead.InvoiceID LIKE '%SNJH%') OR
      (@Keyword = 'SCNHL' AND InvoiceHead.InvoiceID LIKE '%SNJHL%');

SQL Server没有布尔类型。您收到错误消息是因为您的CASE表达式返回的是布尔表达式,但这在SQL Server中不是有效值。

通常,对于WHERE条件使用布尔运算符比引入CASE更简单。