declare @val1 varchar(10) ;
declare @val2 varchar(10) ;
set @val1='s';
set @val2='ur';
EASIEST WAY TO GET THE RESULT IS :-
select * from table_Name where col1=isnull(@val1,col1) and col2=isnull(@val2,col2)
or
use the dynamic SQl code like
declare @val1 varchar(10) ;
declare @val2 varchar(10) ;
declare @dynaimcstring varchar(200);
declare @executestring nvarchar(max);
set @val1 ='s';
set @val2='';
if( ltrim(rtrim(@val1))='' and ltrim(rtrim(@val2))!='')
begin
set @dynaimcstring='where col2='''+@val2+'''';
end
if( ltrim(rtrim(@val1))!='' and ltrim(rtrim(@val2))='')
begin
set @dynaimcstring='where col1='''+@val1+'''';
end
if( ltrim(rtrim(@val1))!='' and ltrim(rtrim(@val2))!='')
begin
set @dynaimcstring=' where col1='''+@val1+''' and col2='''+@val2+'''';
end
if( ltrim(rtrim(@val1))='' and ltrim(rtrim(@val2))='')
begin
set @dynaimcstring='';
end
set @executestring='select * from allot_Det '+ @dynaimcstring;
print @str;
exec sp_executesql @str;