0

如果用户未输入值,则需要编写一个过程来检索未将某些选择标准纳入过程的数据。我正在过滤:

WHERE @ts = [ts] or @username = [username] 
or @ip = [ip] or @my_category = [my_category]
or @my_name = [my_name] or @nm1_name = [nm1_name]
or @param = [param] or @short_descr = [short_descr]

当我调用存储过程并传递过滤工作的参数之一时,当我编写一些时,只有一个过滤工作(因为我的逻辑中有“或”)。替换为 'and' 不满足不必要地传递所有参数,我只需要传递那些我想过滤掉的参数。请帮我解决这个问题

4

2 回答 2

4
WHERE (@ts IS NULL OR [ts] = @ts)
and (@username IS NULL OR [username] = @username)
and (@ip IS NULL OR [ip] = @ip)
and (@my_category IS NULL OR [my_category] = @my_category)
and (@my_name IS NULL OR [my_name] = @my_name)
and (@nm1_name IS NULL OR [nm1_name] = @nm1_name)
and (@param IS NULL OR [param] = @param)
and (@short_descr IS NULL OR [short_descr] = @short_descr)

编辑:

我在对其他答案的评论中看到您传递的是空白字符串而不是 NULL。在这种情况下,您需要处理它们而不是(或另外)NULL

WHERE (@ts IS NULL OR @ts = '' OR [ts] = @ts)
and (@username IS NULL OR @username  = '' OR [username] = @username)
and (@ip IS NULL OR @ip  = '' OR [ip] = @ip)
and (@my_category IS NULL OR @my_category = '' OR [my_category] = @my_category)
and (@my_name IS NULL OR @my_name = '' OR [my_name] = @my_name)
and (@nm1_name IS NULL OR @nm1_name  = '' OR [nm1_name] = @nm1_name)
and (@param IS NULL OR @param  = '' OR [param] = @param)
and (@short_descr IS NULL OR @short_descr = '' OR [short_descr] = @short_descr)
于 2013-06-13T08:00:24.883 回答
3

当您不使用相关过滤器时,您将参数设置为 NULL,对吗?

所以你可以使用这样的查询:

WHERE isnull(@ts, [ts]) = [ts]
and isnull(@username, [username]) = [username] 
and isnull(@ip, [ip]) = [ip]
and isnull(@my_category, [my_category]) = [my_category]
and isnull(@my_name, [my_name]) = [my_name]
and isnull(@nm1_name, [nm1_name]) = [nm1_name]
and isnull(@param, [param]) = [param]
and isnull(@short_descr, [short_descr]) = [short_descr]
option (recompile)

我主张在这种情况下使用选项(重新编译)

编辑:

用 '' 而不是 NULL

WHERE @ts in ('', [ts])
and @username in ('', [username])
and @ip in ('', [ip])
and @my_category in ('', [my_category])
and @my_name in ('', [my_name])
and @nm1_name in ('', [nm1_name])
and @param in ('', [param])
and @short_descr in ('', [short_descr])

(比每次都使用 OR 更具可读性,并且不需要重新编译*)

(*) 作为参数无论如何都不会被嗅探

于 2013-06-13T07:55:50.673 回答