Question

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?

Was it helpful?

Solution 3

This takes care of the middle:

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

Then quote the edges:

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

OTHER TIPS

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

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top