开发者

how to use single quotations inside a transact sql statement

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

for examp开发者_如何转开发le 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?


Just escape the quotes:

change

SET @SQLQuery = ' Select * FROM MyTable WHERE MyTable.Id = '1' '

to

SET @SQLQuery = ' Select * FROM MyTable WHERE MyTable.Id = ''1'' '

** Edit **

To include a local variable in the result, you could updated your query like this:

DECLARE @SQLQuery varchar(200)
DECLARE @tmpInt int

SET @tmpInt = 2
SET @SQLQuery = ' Select * FROM MyTable WHERE MyTable.Id = ' + 
     convert(varchar, @tmpInt) + ' '


Double the single quotes in the quote!

SET @SQLQuery = ' Select * FROM MyTable WHERE MyTable.Id = ''1'' '


Use double ticks to escape them:

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

If you want to use a local variable as you mention in your comment, you can do this:

Declare @SQLQuery AS NVarchar(4000)
Declare @Id AS NVarchar(3)

SET @Id = '1'
SET @SQLQuery = ' Select * FROM MyTable WHERE MyTable.Id= ''' + @Id  + ''''
Execute (@SQLQuery)


wrap the one single quote in to more like ''' and the tics will work as well.


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


Try using double-quotes instead:

SET @SQLQuery = "Select * FROM MyTable WHERE MyTable.Id = '" + @Id + "'"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜