构造T-SQL语句的条件CASE / IF

时间:2014-04-14 15:35:30

标签: sql sql-server case

我在前端代码中有一个查询我正在尝试转换为存储过程。前端代码中包含条件逻辑,用于根据表单值构造正确的SQL。我没有编写原始SQL,但已经负责进行此转换。

我面临的问题是我没有足够的知识/经验去做这件事。我也咨询了这些链接以获得帮助,但他们并没有让我在那里:

SQL: conditional statement in GROUP BY clause

SQL Case statement specifiying condition in where clause?

的伪代码:

WHERE b.ACTIVE=1
  AND YEAR(METRIC_YEAR) = @frmYear

IF @selOrg IS NOT NULL AND @selOrg != 'ALL'
     IF @selOrg = 'org1'
       AND ORG IN('org1','org2','org3') AND MEASURE_ID NOT IN(0,1,2,3,4)
     ELSE
       AND ORG = @selOrg
ELSE
     AND MEASURE_ID NOT IN(0,1,2,3,4)

尝试这样简单的操作会导致“END语法不正确”错误。

WHERE b.ACTIVE=1
  AND YEAR(METRIC_YEAR) = @frmYear
    AND
    CASE @selOrg 
    WHEN 'org1' THEN ORG IN('org1','org2','org3') AND MEASURE_ID NOT IN(0,1,2,3,4)
    END

我想做的是什么?如果是这样,我没有看到什么?

2 个答案:

答案 0 :(得分:0)

你可以这样做:

WHERE b.ACTIVE=1
AND  YEAR(METRIC_YEAR) = @frmYear
AND (
        (@selOrg = 'org1' AND ORG IN('org1','org2','org3') AND MEASURE_ID NOT IN(0,1,2,3,4))
    OR  (@selOrg = 'ALL')
    )

根据您的标准,尽管进行单独的查询可能会有所帮助 -

IF @selOrg = 'org1'
    BEGIN 
        SELECT  ...
        FROM    Table
        WHERE b.ACTIVE=1
        AND  YEAR(METRIC_YEAR) = @frmYear   
        AND ORG IN('org1','org2','org3') 
        AND MEASURE_ID NOT IN(0,1,2,3,4);
    END
ELSE IF @selOrg = 'All'
    BEGIN 
        SELECT  ...
        FROM    Table
        WHERE b.ACTIVE=1
        AND  YEAR(METRIC_YEAR) = @frmYear;
    END

这似乎是额外的工作,但您可能会获得更好的表现。

答案 1 :(得分:0)

"案例"

的例子
SELECT   ProductNumber, Category =
      CASE ProductLine
         WHEN 'R' THEN 'Road'
         WHEN 'M' THEN 'Mountain'
         WHEN 'T' THEN 'Touring'
         WHEN 'S' THEN 'Other sale items'
         ELSE 'Not for sale'
      END,
   Name
FROM Production.Product
ORDER BY ProductNumber;

SELECT   ProductNumber, Name, "Price Range" = 
      CASE 
         WHEN ListPrice =  0 THEN 'Mfg item - not for resale'
         WHEN ListPrice < 50 THEN 'Under $50'
         WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
         WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
         ELSE 'Over $1000'
      END
FROM Production.Product
ORDER BY ProductNumber ;