Thursday, 11 April 2019

Incorrect syntax near ',' in SQL dynamic query or error while passing multi value parameter to dynamic sql

Hi Friends
We encounter the below error when you have to pass multi value paramter in your dynamic sql query


Incorrect syntax near ',' in SQL dynamic query

Scenario

 Declare @SQLQuery AS NVarchar(4000)
 Declare @EN AS NVarchar(2000)
   

Set @EN = ('John Smith,John Micheal')


    Set @SQLQuery = 'Select * From tblEmployees where EmployeeName
IN (''''' +@EN  +''''')'

Exec (@SQLQuery)

We get the error Incorrect syntax near ',' in SQL dynamic query

SOlUTION - Declare another variable and then use replace function to handle the multi value parameters

 Declare @SQLQuery AS NVarchar(4000)
 Declare @EN AS NVarchar(2000)
   

Declare @Ename AS varchar(MAX)

Set @EName = ('John Smith,John Micheal')

SET @EN = REPLACE (@Ename,',',''',''')


    Set @SQLQuery = 'Select * From tblEmployees where EmployeeName
IN (''''' +@EN  +''''')'

Exec (@SQLQuery)


Super!! issue is fixed

No comments:

Post a Comment