查询CASE条件抛出错误

时间:2015-02-16 14:08:00

标签: sql sql-server sql-server-2008 tsql sql-server-2008-r2

我有一个MySQL查询,它工作正常,然后尝试在SQL Server中执行相同的查询但显示错误。

查询是:

SELECT 
    system, tst_env_name 
FROM 
   (SELECT 
       system,tst_env_name, 
       CASE 
          WHEN start_hrs < end_hrs 
            THEN (start_hrs * 60 + start_mins) < 1153 AND 1153 < (end_hrs * 60 + end_mins) 
            ELSE ((start_hrs * 60 + start_mins) < 1153 AND 1153 < 1439) 
                 OR (0 < 1153 AND 1153 < (end_hrs * 60 + end_mins)) 
        END co 
     FROM tst_env_details 
     WHERE project = 'JupitorQA') sub 
WHERE 
    sub.co=0 
    AND system IN ('0', '0.0.0.581');

错误是

  

“&lt;”附近的语法不正确   'co'

附近的语法不正确

我上面的查询做错了什么?

3 个答案:

答案 0 :(得分:0)

你可以像这样使用,我将cons_or start_hr作为字符串,你可以像datatype一样添加SomeValue

SELECT system,tst_env_name 
  FROM (SELECT 
             system,tst_env_name, 
             CASE WHEN 
                  start_hr ='SomeValue' 
             END CASE)

答案 1 :(得分:0)

你不能在select子句中写出直接条件(在使用case之后),而不是像下面那样:

SELECT   stock.name,
      CASE 
         WHEN stock.quantity <20 THEN 'Buy urgent'
         ELSE 'There is enough'
      END
FROM stock

这样会导致错误

select 1 = 1

错误消息:

  
    

Msg 102,Level 15,State 1,Line 1

         

'='附近的语法不正确。

  

答案 2 :(得分:0)

我假设您打算将它们视为布尔表达式,在false时评估为0.

SELECT 
    system, tst_env_name 
FROM 
   (SELECT 
       system,tst_env_name, 
       CASE 
          WHEN start_hrs < end_hrs 
            /* I stripped out the unnecessary comparisons */
            THEN CASE WHEN (start_hrs * 60 + start_mins) < 1153 AND 1153 < (end_hrs * 60 + end_mins) THEN 1 ELSE 0 END
            ELSE CASE WHEN ((start_hrs * 60 + start_mins) < 1153) OR (1153 < (end_hrs * 60 + end_mins)) THEN 1 ELSE 0 END
        END co 
     FROM tst_env_details 
     WHERE project = 'JupitorQA') sub 
WHERE 
    sub.co=0 
    AND system IN ('0', '0.0.0.581');