I'm need to write a stored procedure for SQL Server 2008 for performing a large select
query and I need it to filter results with specifying filtering type via procedure's parameters. I found some solutions like this:
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';
I'm finding that this approach doesn't work. It's possible to cast all the columns to nvarchar(max)
and compare them as strings, but I think it will cause performance degradation.
Is it possible to parametrize the where
clause in stored procedure without using constructs like EXEC sp_executesql
?