0

I want to use where clause in TableName conditional Eg. When my variable @col1 is blank then I dont want to use where with @col1 and it should check for @col2 If @col2 is also blank then return all records. Or else check with their respective conditions/values inside variables.

declare @col1 nvarchar(50)=''
declare @col2 nvarchar(50)=''
select * from TableName
where
(isnull(@col1 ,'')!='' AND col1 =@col1 )
OR
(isnull(@col2 ,'')!='' AND col2 =@col2 )

This returns no record when @col1 or @col2 is blank.

Instead , when both are blank it should return all records, If any one of them contains any value then it should go for that condition.

Edit : Dynamic Sql is not allowed

C Sharper
  • 8,284
  • 26
  • 88
  • 151

3 Answers3

1

Try:

declare @col1 nvarchar(50)=''
declare @col2 nvarchar(50)=''
select * from TableName
where
(isnull(@col1 ,'')='' OR col1 =@col1 )
OR
(isnull(@col2 ,'')='' OR col2 =@col2 )
OPTION (RECOMPILE)

This is the way to handle dynamic conditions without dynamic SQL

George Menoutis
  • 6,894
  • 3
  • 19
  • 43
1

You can trick this using LIKE

declare @col1 nvarchar(50)=''
declare @col2 nvarchar(50)=''
select * from TableName
where
( col1 LIKE ISNULL(@col1, '%' )
AND
( col2 LIKE ISNULL(@col2, '%' )

when @variable is null, it will set to filter LIKE '%' which return all values

And i changed to logic into AND, because, with assumption, if both @variable have values, then shouldn't it be display data that qualify both values? Which leads to AND logic. This may need to be consider

Alfin E. R.
  • 741
  • 1
  • 7
  • 24
1

create dynamic query for this

DECLARE @COL1 NVARCHAR(50)=''

DECLARE @COL2 NVARCHAR(50)=''

DECLARE @SQL NVARCHAR(500)

SET @SQL='SELECT * FROM TABLENAME'

IF(@COL1!='')
BEGIN

SET @SQL=@SQL+' WHERE COL1='+@COL1+''

END EXEC @SQL

pankaj singh
  • 95
  • 10