参数化WHERE子句?

con*_*low 5 sql parameters stored-procedures sql-server-2008

我需要为SQL Server 2008编写一个存储过程来执行大型select查询,我需要它来过滤结果,并通过过程的参数指定过滤类型.我发现了一些这样的解决方案:

create table Foo(
   id bigint, code char, name nvarchar(max))
go

insert into Foo values
 (1,'a','aaa'),
 (2,'b','bbb'),
 (3,'c','ccc')
go

create procedure Bar
       @FilterType  nvarchar(max),
       @FilterValue nvarchar(max) as
begin
    select * from Foo as f
    where case @FilterType
          when 'by_id'   then f.id
          when 'by_code' then f.code
          when 'by_name' then f.name end
          = 
          case @FilterType
          when 'by_id'   then cast(@FilterValue as bigint)
          when 'by_code' then cast(@FilterValue as char)
          when 'by_name' then @FilterValue end
end
go

exec Bar 'by_id', '1';
exec Bar 'by_code', 'b';
exec Bar 'by_name', 'ccc';
Run Code Online (Sandbox Code Playgroud)

我发现这种方法不起作用.可以将所有列转换nvarchar(max)为字符串并将它们作为字符串进行比较,但我认为这会导致性能下降.

是否可以where在不使用类似构造的情况下参数化存储过程中的子句EXEC sp_executesql

Pad*_*ddy 2

对于大型过滤器要求,这可能会变得有点冗长,但我认为它可能更高效/更易于阅读/维护:

create procedure Bar
       @Id int,
       @Code nvarchar,
       @name nvarchar
begin
    select * from Foo as f
    where (@id = -1 or f.ID = @id)
    and (@Code = '' or f.Code = @Code)
    and (@Name = '' or f.Name = @Name)
end
go

exec Bar 1, '', ''
exec Bar -1, 'code', ''
exec Bar -1, '', 'name'
Run Code Online (Sandbox Code Playgroud)

这还允许您同时过滤多个项目。