4

I have a sql table which has one column "type". It has values A,B,C,D.
I'm writing a stored procedure in which type is the in parameter @type.
@type can has either value 'A' or 'A,B,C' or 'ALL' based on user selection on screen. Which means user can select single,multiple or ALL options.
I need to filter data from my table with condition on column "type".

I want something similar to below

select * from maintable where
( case when @type ='ALL' then 1=1) else
 type in (select data from SplitString(@type,',')) end)  

I have written a split function which return values in a table format.

When ALL is selected then the whole table should be returned. When specific type(s) is selected, only those types should be returned.

I'm using sqlserver 2012.
Kindly help!!

CrazyCoder
  • 2,194
  • 10
  • 44
  • 91

3 Answers3

3

Try this

SELECT * 
FROM maintable 
WHERE @type ='ALL' OR    
(@type <>'ALL' AND TYPE IN (SELECT data FROM SplitString(@type,','))
Danieboy
  • 4,393
  • 6
  • 32
  • 57
Jayasurya Satheesh
  • 7,826
  • 3
  • 22
  • 39
0

You can do it like below :

if @type ='ALL' 
    set @type ='A,B,C,D'

select * from maintable where
type in (select data from SplitString(@type, ','))
Md. Suman Kabir
  • 5,243
  • 5
  • 25
  • 43
0

You can use an IF:

IF @type ='ALL'
    SELECT *
    FROM MainTable
        ELSE
            SELECT *
            FROM MainTable
            WHERE Type IN (SELECT data FROM SplitString(@type,',') )
Ilyes
  • 14,640
  • 4
  • 29
  • 55