简体   繁体   中英

Dynamic Query based on SSRS parameter value

I have a procedure that returns a set of values. I have a SSRS Parameter that will show or hide columns based on values.

My stored procedure select query looks like:

SELECT DISTINCT 
    t1.Col1,
    t2.Col1
FROM 
    Table1 t1
    INNER JOIN Table2 t2
    ON t1.ID = t2.ID
WHERE
    t1.col1 LIKE '%SomeValue%' OR 
    t2.col1 LIKE '%SomeValue%'

With a result set of:

t1.Col1 | t2.Col1
    a   |   d
    a   |   e
    a   |   f

The problem is that even if the checkbox is unticked in the report, the stored procedure is still showing multiple records like so:

With Col2 unticked in report parameter:

t1.Col1
    a   
    a   
    a 

How would I go about changing the stored procedure to accept 1 parameter that can have multiple values and change the query to add/remove a column from the SELECT and WHERE statement?

So with Col2 unticked, the stored procedure might be something like:

SELECT DISTINCT 
    t1.Col1
FROM 
    Table1 t1
    INNER JOIN Table2 t2
    ON t1.ID = t2.ID
WHERE
    t1.col1 LIKE '%SomeValue%'

And returns:

t1.Col1 
   a

you can you use EXECUTE

DECLARE @sql VARCHAR(max)
set @sql='SELECT '+ CASE WHEN @param2 IS NOT NULL THEN 't2.Col1' ELSE '' END +'  FROM t1'+
CASE WHEN @param2 IS NOT NULL THEN 'INNER JOIN Table2 t2  ON t1.ID = t2.ID' ELSE '' END
EXECUTE( @sql)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM