how to use single quotations inside a transact sql statement

Viewed 45382

i want use single quotations inside a transact sql statement, then execute that statement.

for example my query is:

Select * FROM MyTable WHERE MyTable.Id = '1'

now i want use like this:

Declare @SQLQuery AS NVarchar(4000)
SET @SQLQuery = ' Select * FROM MyTable WHERE MyTable.Id = '1' '
Execute (@SQLQuery)

this not work, and this error occurred :

Invalid column name '1'

I know problem is quotations in left and right side of the 1

this is a sample and i want use of this way to a large query

of course, i want use local variable instead for example '1' and my local variable is varchar

any idea?

6 Answers

To make a more reader-friendly code I use a variable for the single quote:

Declare @chrSQ char(1) = CHAR(39); --Single quote

SET @SQLQuery = 'Select * FROM MyTable WHERE MyTable.Id = ' + @chrSQ + @Id + @chrSQ + ';'

/Flemming

Related