使用空过滤器作为参数处理T-SQL查询

时间:2012-09-21 14:55:42

标签: sql-server-2008 tsql parameters filter null

假设我有一个存储过程,我将5个过滤器作为参数传递。这些参数是我查询中每列的过滤器。我的查询有5个字段。如果我的过滤器有一个或多个NULL(或'')值参数,那么阻止我的查询抛出异常/错误的最佳方法是什么?

    SELECT 
        [helpings_turkey],
        [helpings_green_beans],
        [scoops_squash],
        [qty_buscuits],
        [pieces_pie]
    FROM
        [thanksgiving_guest]
    WHERE 
        [helpings_turkey] > @helpings_turkey_filter
        AND [helpings_green_beans] > @helpings_green_beans_filter
        AND [scoops_squash] > @scoops_squash_filter
        AND [qty_buscuits] > @qty_buscuits_filter
        AND [pieces_pie] > @pieces_pie_filter

3 个答案:

答案 0 :(得分:2)

好吧,如果值为null,您将不会收到错误,但您也不会得到结果。

你可以这样做:

[helpings_turkey] > ISNULL(@helpings_turkey_filter, X)

其中“X”是你知道的小于你的最小值。

这适用于小型数据集,但可能无法利用您在[thanksgiving_guest]表格上的任何索引。

在这样的模式中执行过滤器的最高效方法是通常通过在遇到非空过滤条件时插入子句来动态组装SQL,如下所示:

SET @sql = 'SELECT 
        [helpings_turkey],
        [helpings_green_beans],
        [scoops_squash],
        [qty_buscuits],
        [pieces_pie]
    FROM
        [thanksgiving_guest]
    WHERE 1=1';

IF @helpings_turkey_filter IS NOT NULL BEGIN
    SET @sql = @sql + '[helpings_turkey] > @helpings_turkey_filter'
END
...
IF @pieces_pumpkin_pie_filter IS NOT NULL BEGIN
    SET @sql = @sql + '[pieces_pumpkin_pie] > @pieces_pumpkin_pie_filter'
END

exec sp_executesql @sql, N'@helpings_turkey_filter, ..., @pieces_pumpkin_pie_filter', @helpings_turkey_filter, @pieces_pumpkin_pie_filter`

请注意,即使我们动态组装查询,我们仍会继续参数化查询。

答案 1 :(得分:1)

 SELECT 
        [helpings_turkey],
        [helpings_green_beans],
        [scoops_squash],
        [qty_buscuits],
        [pieces_pie]
    FROM
        [thanksgiving_guest]
    WHERE 
        [helpings_turkey] > IsNull(@helpings_turkey_filter, 0)
        AND [helpings_green_beans] > IsNull(@helpings_green_beans_filter, 0)
        AND [scoops_squash] > IsNull(@scoops_squash_filter, 0)
        AND [qty_buscuits] > IsNull(@qty_buscuits_filter, 0)
        AND [pieces_pumpkin_pie] > IsNull(@pieces_pumpkin_pie_filter, 0)

像这样的东西。如果参数传入,则使用该参数,如果不是默认值,则使用该参数。我默认为零。

答案 2 :(得分:1)

试试这个,因为这会解决你的问题(如果你传递的参数可能是多个NULL:

SELECT 
        [helpings_turkey],
        [helpings_green_beans],
        [scoops_squash],
        [qty_buscuits],
        [pieces_pie]
    FROM
        [thanksgiving_guest]
    WHERE 
        [helpings_turkey] > ISNULL(@helpings_turkey_filter, 0)
        AND [helpings_green_beans] > ISNULL(@helpings_green_beans_filter, 0)
        AND [scoops_squash] > ISNULL(@scoops_squash_filter, 0)
        AND [qty_buscuits] > ISNULL(@qty_buscuits_filter, 0)
        AND [pieces_pumpkin_pie] > ISNULL(@pieces_pumpkin_pie_filter, 0)