TSQL Passing MultiValued Reporting Services Parameter into Dynamic SQL

半世苍凉 提交于 2020-01-14 06:49:09

问题


Duplicate of: TSQL varchar string manipulation

I'm building a dynamic SQL statement out of parameters from a reporting services report. Reporting services passes MutiValue Parameters in a basic CSV format. For example a list of states may be represented as follows: AL,CA,NY,TN,VA

In a SQL statement this is OK:

WHERE customerState In (@StateList) 

However, the dynamic variant isn't OK:

SET @WhereClause1 = @WhereClause1 + 'AND customerState IN (' + @StateList + ') '

This is because it translates to (invalid SQL):

AND customerState IN (AL,CA,NY,TN,VA)

To process it needs something like this:

AND customerState IN ('AL','CA','NY','TN','VA')

Is there some cool expression I can use to insert the single quotes into my dynamic SQL?


回答1:


REPLACE didn't work for me when used with IN for some reason. I ended up using CHARINDEX

WHERE CHARINDEX( ',' + customerState + ',', ',' + @StateList + ',' ) > 0



回答2:


For anyone attempting to use Dynamic SQL with a multi-valued parameter in the where clause AND use it to run an SSRS report, this is how I got around it...

create table #temp
(id, FName varchar(100), LName varchar(100))

declare @sqlQuery (nvarchar(max))
set @sqlQuery =
'insert into #temp
select 
id, 
FName, 
LName 
from dbo.table'
exec (@sqlQuery)

select 
FName, LName
from #temp
where #temp.id in (@id) -- @id being an SSRS parameter!

drop table #temp

Granted, the problem with this query is that the dynamic SQL will select everything from dbo.table, and then the select from #temp is where the filter kicks in, so if there's a large amount of data - it's probably not so great. But... I got frustrated trying to get REPLACE to work, or any other solutions others had posted.




回答3:


This takes care of the middle:

SET @StateList = REPLACE(@StateList, ',', ''',''')

Then quote the edges:

SET @WhereClause1 = @WhereClause1 + 'AND customerState IN (''' + @StateList + ''') '



来源:https://stackoverflow.com/questions/712430/tsql-passing-multivalued-reporting-services-parameter-into-dynamic-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!