Edit query based on parameters in SQL Reporting Services
Is it possible to change a qu开发者_运维问答ery in Reporting Services based on a parameter?
I'd like to be able to change table names within the query from tableName to tableName2 (for example) on the fly.
There are two ways you could do it:
- Write multiple queries (one for each table), then switch among then based upon the parameter value
- Use dynamic SQL
For 1, you'd do something like this:
if @param = 'value'
select Col1, Col2 from Table1
else
select Col1, Col2 from Table2
For 2, you'd do something like this:
declare @sql nvarchar(4000)
select @sql = 'select Col1, Col2 from' + (case when @param = 'value' then 'Table1' else 'Table2' end)
sp_executesql @sql
WARNING: Be very careful of option 2. If option 1 is feasible, then it is the safer option, as dynamically constructing SQL based upon user-supplied values is always a dangerous affair. While this particular example doesn't use the parameter directly in the SQL, it would be very easy to write something that did, and thus very easy to find a way to exploit it.
精彩评论