where子句中的动态T-SQL存储过程

时间:2019-05-12 09:57:46

标签: sql-server tsql stored-procedures

我需要编写一个带有以下两个参数的示例存储过程:

sp_list_customers @locationid int, @category varchar

用户可以传递@locationid = 0来列出所有位置或特定位置ID的客户。他们还可以将null或空字符串传递给p以减慢所有类别。

这是我的SQL代码:

create procedure ...
as 
    select * 
    from customers
    where locationid = (case 
                           when isnull(@locationid, 0) = 0 
                              then locationid 
                              else @locationid  
                        end)
      and category = (case 
                         when isnull(@category, '') = '' 
                            then category 
                            else @category 
                      end)

但是,使用更多参数时,此类代码运行太慢

我一直在寻找解决问题的方法,然后发现动态T-SQL是可以接受的解决方案。但是迁移我所有的存储过程是一场噩梦,容易出错。

我需要编写另一个用户定义的函数来帮助我。最好的用户定义功能代码是什么?

谢谢

1 个答案:

答案 0 :(得分:0)

尝试下面的简化代码效果更好...

create procedure ... as select * from customers where (nullif(@locationid,'') is null
  or locationid = @locationid)
 and (   nullif(@category,'') is null or category = @category)