How to use Pass comma separated string in dynamic query in SQL

后端 未结 2 1071
鱼传尺愫
鱼传尺愫 2021-01-22 04:30

I have a function which will return integer values from comma delimited string , It takes two parameters (@string nvarchar(4000), @delimiter char(1)). So the problem is if I am

2条回答
  •  后悔当初
    2021-01-22 04:57

    When you build a dynamic SQL like that, you need to wrap your parameter in double quote ''

    declare @ProductIDs varchar(11)
    declare @SQL varchar(max)
    
    set @ProductIDs='1,2,3,4'
    declare @query varchar(max)
    --set @query= @ProductIDs +','+@Delimiter
    
    SELECT @SQL = 'SELECT val FROM dbo.[fnDelimitedStringToTable]('''+ @ProductIDs +''' , '','')'
    
    Exec(@SQL)
    

    This way the SQL statement will be:

    SELECT val FROM dbo.[fnDelimitedStringToTable]('1,2,3,4' , '','')
    

    and not:

    SELECT val FROM dbo.[fnDelimitedStringToTable](1,2,3,4 , '','')
    

提交回复
热议问题