0

假设我有一个存储过程,其中我将 5 个过滤器作为参数传递。这些参数是我查询中每一列的过滤器。我的查询有 5 个字段。如果我的过滤器有 1 个或多个 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
4

3 回答 3

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`

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

于 2012-09-21T15:03:58.300 回答
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)
于 2012-09-21T15:09:54.607 回答
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)

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

于 2012-09-21T14:59:25.927 回答