Shaiwal Tripathi Shaiwal Tripathi - 5 months ago 14
SQL Question

How to parameterize query with special character in SQL Server?

I want to execute a query with concatenation of two columns so I have done this:

Select
Id, PtName + ' ('+Investigation+')' as PtName, Y, M, D, PtCode
From
DiagMain


But when I am trying to parameterize this query, it's not working.

Like this:

declare @Query nvarchar(MAX)

set @Query = 'Select Id, PtName + ''( +''Investigation''+ )'' as PtName, Y, M, D, Sex, PtCode FROM DiagMain'
Exec(@Query)


What I am doing wrong here?

Answer Source

Your single quotes were misplaced, they should surround the brackets ( & ):

set @Query = 'Select Id, PtName + ''('' +Investigation+ '')'' as PtName, Y, M, D, Sex, PtCode FROM DiagMain'

You could debug this by using the print command:

print @Query