存储过程过滤

时间:2013-06-13 07:50:55

标签: sql sql-server tsql

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

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]

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

2 个答案:

答案 0 :(得分: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。在这种情况下,您需要替代(或另外)处理NULLs

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)

答案 1 :(得分: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更具可读性,并且不需要重新编译*)

(*)因为参数不会被嗅探