x
login about faq Site discussion (meta-askssc)

Incorrect Syntax on Declared VarChar

declare @sql varchar(max)
declare @colnm varchar(max)
declare @PDSLINEID varchar(max)

set @sql  = ''
set @colnm = 'CHKISODATA11'
set @PDSLINEID = '2500999YN8888'

select @sql  = 'SELECT ' + @colnm + ' 
FROM PDTABLE_FABISOS 
WHERE CHKISODATA15 = ' + @PDSLINEID + ''

EXEC (@sql)

results in an error from SQL Server 2008: ...incorrect syntax near 'YN8888'... Why would SQL do this when it is declared as a varchar?

more ▼

asked May 08 '12 at 05:05 PM in Default

SheldonMcc gravatar image

SheldonMcc
0 1 1 1

(comments are locked)
10|1200 characters needed characters left

1 answer: sort newest

The "incorrect syntax near 'YN8888'" error is generated by the EXEC (@sql) line.

It is not due to the SET @PDSLINEID... line, but to the SELECT... line immediately following it.

If you change that line as follows, all should be good:

SELECT @sql = 'SELECT ' + @colnm + ' FROM PDTABLE_FABISOS 
    WHERE CHKISODATA15 = ''' + @PDSLINEID + ''''

Here we are wrapping the @PDSLINEID value in quotes, as it is a string.

You can help keep an eye out for these things when developing your code by putting in SELECT @sql before you try to execute the command - that'll show you if you're about to run the right thing or not.

more ▼

answered May 08 '12 at 05:13 PM

ThomasRushton gravatar image

ThomasRushton ♦
30.1k 7 10 40

Thomas,

Awesome, thanks so much for you help. It works. Have a great day!

May 08 '12 at 05:36 PM SheldonMcc
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments



Facebook logo Follow Ask SSC on Facebook
Find Ask SSC on Google+
linkedin logo Find us on LinkedIn

Topics:

x1611
x12

asked: May 08 '12 at 05:05 PM

Seen: 587 times

Last Updated: May 09 '12 at 02:16 PM

Copyright © 2002-2012 Simple Talk Publishing. All Rights Reserved. If you have any queries, please contact the site administrators.
Ask SQL Server Central is a community service provided by Red Gate.