SQL子查询如果为null则不执行

时间:2009-07-23 16:52:11

标签: asp.net sql stored-procedures

我想知道如果我的@ ID1为NULL,是否有办法不执行我的子查询?

CREATE PROCEDURE [dbo].[TestTable_Search]
    @Col1 int,
    @Col2 uniqueidentifier,
    @Col3 datetime,
    @Col4 datetime,
    @ID1 varchar(10)
AS

SET TRANSACTION ISOLATION LEVEL READ COMMITTED

SELECT *

FROM
    [dbo].[TestTable]
WHERE
    [Col1] = COALESCE(@Col1, Col1) AND
    [Col2] = COALESCE(@Col2, Col2) AND
    [Col3] >= COALESCE(@Col3 + "00:00:00", Col3) AND
    [Col4] <= COALESCE(@Col4 + "23:59:59", Col4) AND
    [Col5] IN (SELECT [ID2] FROM [dbo].[TestTable2] WHERE [ID1] =  @ID1)

3 个答案:

答案 0 :(得分:2)

不确定你的意思,但也许这就是你要找的东西:

SELECT *
FROM
    [dbo].[TestTable]
WHERE
    [Col1] = COALESCE(@Col1, Col1) AND
    [Col2] = COALESCE(@Col2, Col2) AND
    [Col3] >= COALESCE(@Col3 + "00:00:00", Col3) AND
    [Col4] <= COALESCE(@Col4 + "23:59:59", Col4) AND (
    @ID1 IS NULL 
        OR [Col5] IN (SELECT [ID2] FROM [dbo].[TestTable2] WHERE [ID1] =  @ID1))

答案 1 :(得分:1)

SQL Server在处理OR条件方面不是很好,特别是在变量上,这就是为什么这可能是最好的决定:

SELECT  *
FROM    [dbo].[TestTable]
WHERE   [Col1] = COALESCE(@Col1, Col1) AND
        [Col2] = COALESCE(@Col2, Col2) AND
        [Col3] >= COALESCE(@Col3 + "00:00:00", Col3) AND
        [Col4] <= COALESCE(@Col4 + "23:59:59", Col4) AND
        AND @id1 IS NULL
UNION ALL
SELECT  *
FROM    [dbo].[TestTable]
WHERE   [Col1] = COALESCE(@Col1, Col1) AND
        [Col2] = COALESCE(@Col2, Col2) AND
        [Col3] >= COALESCE(@Col3 + "00:00:00", Col3) AND
        [Col4] <= COALESCE(@Col4 + "23:59:59", Col4) AND
        [Col5] IN (SELECT [ID2] FROM [dbo].[TestTable2] WHERE [ID1] =  @ID1)

如果@id不是NULL,则第一个子查询将不会返回任何内容,因为过滤器。

如果@idNULL,则第二个子查询将不返回任何内容,因为与NULL的比较从不匹配,内部子查询将返回空集,并且{{1}永远不会满足。

col5 IN (SELECT …)可以在运行时有效地检测这些内容,这就是为什么第二个子查询中的第一个几乎立即被优化出来的原因。

在我的博客中查看此文章,了解SQL ServerOR的效果比较:

答案 2 :(得分:0)

如果不执行子查询,则无论如何都不会返回任何行。所以只需使用单独的SELECT来处理这种情况:

IF @ID1 IS NULL
BEGIN

    SELECT *
    FROM dbo.[TestTable]
    WHERE 1 = 0

END
ELSE
BEGIN

    SELECT *

    FROM
        [dbo].[TestTable]
    WHERE
        [Col1] = COALESCE(@Col1, Col1) AND
        [Col2] = COALESCE(@Col2, Col2) AND
        [Col3] >= COALESCE(@Col3 + "00:00:00", Col3) AND
        [Col4] <= COALESCE(@Col4 + "23:59:59", Col4) AND
        [Col5] IN (SELECT [ID2] FROM [dbo].[TestTable2] WHERE [ID1] =  @ID1)

END