sql server - Building where clause based on null/not null parameters in sql -
i trying create stored procedure return records based on input. if input parameters null, return entire table, else use parameters , return records:
create procedure getrecords @parm1 varchar(10) = null, @parm2 varchar(10) = null, @parm3 varchar(10) = null declare @whereclause varchar(500) set @whereclause = ' 1 = 1 ' if (@parm1 null , @parm2 null , @parm3 null) select * dummytable else begin if (@parm1 not null) set @whereclause += 'and parm1 = ' + '' + @parm1 + '' if (@parm2 not null) set @whereclause += 'and parm2 = ' + '' + @parm2 + '' if (@parm3 not null) set @whereclause += 'and parm3 = ' + '' + @parm3 + '' select * dummytable @whereclause <-- error end
error while creating procedure "an expression of non-boolean type specified in context condition"
please comment if approach wrong in building clause?
thanks
the entire query should in varchar , can executed using "exec" function.
set @query = "select * dummytable 1=1 " ... if clauses ... exec(@query)
hth.
Comments
Post a Comment