带有case&的sql where子句喜欢

时间:2012-06-30 13:58:24

标签: sql mysqli

块引用

DECLARE @Symbol nvarchar(50);
DECLARE @EnDate1 Datetime;
DECLARE @StDate1 Datetime;
SET @Symbol = 'RIM12f'
SET @EnDate1 = '05/08/2012 9:00'
SET @StDate1 = '05 / 07 / 2012 12 : 00'
SELECT  *
FROM   Siri
WHERE (DATEADD(D, 0, DATEDIFF(D, 0, Date)) BETWEEN @StDate1 AND @EnDate1)
  AND  CASE Symbol = WHEN @Symbol = 'ALL'
                     THEN Symbol
                     ELSE Symbol LIKE LEFT(@Symbol, len(@Symbol) - 3) + '%'
       END

它不起作用但是 它适用于@Symbol 但我需要所有符号,如LEFT(@Symbol,len(@Symbol) - 3)+'%'如果@Symbol除了所有

3 个答案:

答案 0 :(得分:2)

修改案例表达式:

 Symbol LIKE CASE @Symbol WHEN 'ALL'
                     THEN Symbol
                     ELSE LEFT(@Symbol, len(@Symbol) - 3) + '%'

答案 1 :(得分:0)

DECLARE @Symbol nvarchar(50); 
DECLARE @LikeSymbol nvarchar(50); 

DECLARE @EnDate1 Datetime; 
DECLARE @StDate1 Datetime; 
SET @Symbol = 'RIM12f' 
SET @EnDate1 = '05/08/2012 9:00' 
SET @StDate1 = '05 / 07 / 2012 12 : 00' 
SET @LikeSymbol = LEFT(@Symbol, length(@Symbol) - 3) + '%'
SELECT  * 
FROM   Siri 
WHERE (DATEADD(D, 0, DATEDIFF(D, 0, Date)) BETWEEN @StDate1 AND @EnDate1) 
AND (
(@Symbol = 'All')
OR
(Symbol Like @LikeSymbol)
)

猜测您的查询意图远​​非明确

答案 2 :(得分:0)

您不能CASE =和嵌套LIKE ..您可以使用LIKE或使用ORAND结构...(如建议的那样) @Tony Hopkinson)

以下是修改过的案例:

Symbol like CASE WHEN @Symbol = 'ALL'
                     THEN Symbol
                     ELSE LEFT(@Symbol, len(@Symbol) - 3) + '%'
END