如何检查sqlserver

时间:2016-12-15 12:23:34

标签: sql-server

我有一个要求,需要检查CASE语句的THEN子句中的条件。请在下面找到示例

SELECT *
FROM SampleTable t
WHERE 
    CASE
    WHEN (t.producttypeid = 1)
        THEN (CAST(CONVERT(NVARCHAR(30), CAST(t.releasedate AS DATETIME), 111) AS DATETIME) >= CAST(CONVERT(NVARCHAR(30), CAST(t.createddate AS DATETIME), 111) AS DATETIME)) 
    WHEN (t.producttypeid IN (2, 3))
        THEN (CAST(CONVERT(NVARCHAR(30), CAST(t.createddate AS DATETIME), 111) AS DATETIME) >= CAST(CONVERT(NVARCHAR(30), CAST(t.releasedate AS DATETIME), 111) AS DATETIME))
    END

上述查询的解释:在上面查询的where子句中,我使用case语句检查producttypeid,并根据producttypeid的值,我必须检查releaseate和createddate的日期。

但上面的查询会给出以下语法错误:

  

*'>'附近的语法不正确。

     

')'。*

附近的语法不正确

我通过使用两个select语句并使用union分隔where子句来完成上述任务。请在下面查询

SELECT *
FROM SampleTable t
WHERE CAST(CONVERT(NVARCHAR(30), CAST(t.releasedate AS DATETIME), 111) AS DATETIME) >= CAST(CONVERT(NVARCHAR(30), CAST(t.createddate AS DATETIME), 111) AS DATETIME)) 
UNION
SELECT *
FROM SampleTable t
WHERE CAST(CONVERT(NVARCHAR(30), CAST(t.createddate AS DATETIME), 111) AS DATETIME) >= CAST(CONVERT(NVARCHAR(30), CAST(t.releasedate AS DATETIME), 111) AS DATETIME))

所以日期检查应该在THEN子句中根据CASE语句完成。

但我希望通过单选查询实现上述任务。请帮我这方面。

提前致谢。

1 个答案:

答案 0 :(得分:2)

你可以用一些布尔代数来实现这一点。试试这个:

SELECT * FROM SampleTable t WHERE t.producttypeid IN (1, 2, 3) AND ((
    t.producttypeid = 1 AND (
        CAST(CONVERT(NVARCHAR(30), CAST(t.releasedate AS DATETIME), 111) AS DATETIME) >= CAST(CONVERT(NVARCHAR(30), CAST(t.createddate AS DATETIME), 111) AS DATETIME)
    )
) OR (
    t.producttypeid IN (2, 3) AND (
        CAST(CONVERT(NVARCHAR(30), CAST(t.createddate AS DATETIME), 111) AS DATETIME) >= CAST(CONVERT(NVARCHAR(30), CAST(t.releasedate AS DATETIME), 111) AS DATETIME)
    )
))