Search code examples
sqlsql-serversql-server-2008sql-like

Can I pass in several strings to one parameter in Dynamic SQL?


I am trying to pass several strings into one parameter called '@Portfolio', and use the LIKE clause. Is that possible? Something like this.

Declare @AsOfDate varchar(10)
Declare @PID varchar(5)
Declare @Portfolio varchar(20)
Declare @sqlCommand  varchar(max)
Set @AsOfDate = '04/30/2018'
Set @Portfolio = 'Treasury Investment,CASH,Derivatives,Wholesale Funding'
Set @PID = 'I.A.6'

...etc...

WHERE ((Tgt_DO.PID like ' + '''' + @PID + '''' + ' AND Tgt_DO.Portfolio like ' + '''' + @Portfolio + '''' + ' And Tgt_DO.AsOfDate = ' + '''' + @AsOfDate + '''' + '))'

I am on SQL Server 2008.


Solution

  • To elaborate on the comments... since you use LIKE in some cases you'll need to concate the %

    where
        Tgt_DO.PID like '%' + @PID + '%'
        and Tgt_DO.Portfolio like '%' + @Portfolio + '%'
        and Tgt_DO.AsOfDate = @AsOfDate
    

    This could bring back unintended results since @Portfolio is a comma separated string. I would use a Table-Valued Parameter or split them into a temp table or table variable using a splitter, like this answer