如果value为null,则跳过Condtion

时间:2017-11-15 22:31:20

标签: sql-server

这应该很简单;但是,我无法使用CASE语句包围它。

DECLARE @Test INT = NULL
SELECT *
FROM StoreImages
WHERE Quality = 1 AND Ready = @Test

我想完成类似的事情:

DECLARE @Test INT = NULL
SELECT *
FROM StoreImages
CASE @Test IS NOT NULL
  WHERE Quality = 1 AND Ready = @Test
ELSE
  WHERE Quality = 1

更新

我创建了一个架构示例,用于快速测试提供的答案

--create a temporary table
CREATE TABLE #ImagesTable(
Quality BIT,
Ready BIT)

-- insert into the temporary table
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1); 
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1); 
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1); 
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1); 
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1); 
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0); 
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0); 
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0); 
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0); 
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0); 
  • 将@Test声明为null应返回所有
  • 将@Test声明为1或0应返回半记录

3 个答案:

答案 0 :(得分:2)

我会这样做:

DECLARE @Test INT = NULL
SELECT *
FROM #ImagesTable 
WHERE (Quality = 1 AND Ready = @Test) OR Quality = 1;

您可以使用CASE 如果,则值可以在@Test而不是NULL中,如:

DECLARE @Test INT = NULL
SELECT *
FROM #ImagesTable 
WHERE Quality = 1 AND Ready = (CASE WHEN @Test IS NULL THEN 1 ELSE @Test END);

更新

我可以看到0列中只有1Ready两个值:

SELECT *
FROM #ImagesTable 
WHERE (Quality = 1 AND Ready IN ( ISNULL(@Test, 0), ISNULL(@Test, 1) ) );

以下是 Demo ,您可以在这里玩。

答案 1 :(得分:1)

通常,在可空参数周围使用ISNULL或CASE表达式是不好的做法。根据查询的复杂性,它可能会对优化器造成严重破坏,从而导致查询计划选择不佳。

使用IF来突破您的查询,而不是使用CASE:

DECLARE @Test int = NULL;

IF @Test IS NULL BEGIN
    SELECT *
    FROM #ImagesTable IT
    WHERE IT.Quality = 1;
END ELSE BEGIN
    SELECT *
    FROM #ImagesTable IT
    WHERE IT.Quality = 1
      AND IT.Ready = @Test;
END

第一个答案萨米会给你带来OR的问题。无论@Test的值如何,如果质量为1,将返回一行。

编辑: 如果 使用类似于CASE表达式的东西,那么正确的语法将是:

SELECT *
FROM #ImagesTable IT
WHERE IT.Quality = 1
  AND (IT.Ready = @Test OR @Test IS NULL);

答案 2 :(得分:0)

我想你想要

SELECT *
FROM #ImagesTable 
WHERE Quality IS NULL
OR    (
        Quality = 1   AND
        Ready = @Test
      )