HowTo dynamic SQL
How to dynamic SQL. three examples on using dynamic sql.
Last updated:
Warning: Review and test in a non-production environment before running.
-- chaos
create proc...
declare @par1 int = null,
@par2 ....
select ....
from ....
where col1 = coalesce(@par1,col1)
and col2 = coalesce(@par2,col2)
and (col3 = @par3 or @par3 is not null)
and col4 = coalesce(@par4,col4)
-- less chaos
create proc...
declare @par1 int = null,
@par2 ....
@str nvarchar(max) = N'select col1,col2.....
from table
where 1 = 1'; -- 1=1 return all rows and prepare for the next columns check
set @str = case when @par1 is not null then N' AND col1 = @par1' else '' end +
case when @par2 is not null then N' AND col2 = @par2' else '' end +
case when @par3 is not null then N' AND col3 = @par3' else '' end +
case when @par4 is not null then N' AND col4 = @par4' else '' end
-- if the query return large diff of rows then use the next statement.
-- set @str += N' OPTION (RECOMPILE);
exec sp_executesql @str,
N'@par1 int, @par2 int, @par3 int, @par4 int',
@par1,@par2,@par3,@par4;
-- bad chaos
create proc...
declare @par1 int = null,
@par2 ....
@str nvarchar(max) = N'select col1,col2.....
from table
where 1 = 1';
if @par1 is not nul
set @str += N' AND col1 = ' + CONVERT(VARCHAR(12), @par1);
if @par2 is not nul
set @str += N' AND col2 = ' + CONVERT(VARCHAR(12), @par2);
if @par3 is not nul
set @str += N' AND col3 = ' + CONVERT(VARCHAR(12), @par3);
if @par4 is not nul
set @str += N' AND col4 = ' + CONVERT(VARCHAR(12), @par4);