views:

384

answers:

4

here's my code:

DECLARE @SQL varchar(600)

SET @SQL = 
'SELECT     CategoryID, SubCategoryID, ReportedNumber
FROM    tblStatistics
WHERE   UnitCode = ' + @unitCode +
' AND   FiscYear = ' + @currYEAR

EXEC (@SQL)

When i run this sproc with unitCode = 'COB' and currYEAR = '10', i get the following error:

Invalid column name 'COB'.

Does anyone know why?

thx!

+5  A: 

You need to put quotes around the values in the SQL:

'SELECT     CategoryID, SubCategoryID, ReportedNumber
FROM    tblStatistics
WHERE   UnitCode = ''' + @unitCode +
''' AND   FiscYear = ''' + @currYEAR + ''''
Mark Byers
thank you! that makes sense now
Daria
+6  A: 

That's a nice SQL injection vulnerability there.

Start by rewriting it this way, using bind parameters:

DECLARE @SQL nvarchar(4000)

SET @SQL =
    'SELECT CategoryID, SubCategoryID, ReportedNumber ' +
    'FROM tblStatistics ' +
    'WHERE UnitCode = @UnitCode ' +
    'AND FiscYear = @CurrYear'

EXEC sp_executesql
    @SQL,
    '@UnitCode varchar(10), @CurrYear int',
    @UnitCode = 'COB',
    @FiscYear = 10
Aaronaught
i'm doind sql injection tests elsewhere, but thank you!
Daria
@Daria: What? You don't do SQL injection "tests", you design your scripts and code to prevent it in the first place. The code you posted is a SQL injection vulnerability - period. This is the *only* correct way to write dynamic SQL with parameters, and it will solve your error here at the same time.
Aaronaught
+3  A: 

You don't have quotes inside your quotes - SQL essentially sees

WHERE UnitCode = COB

and COB must not be a column. But why are you building the SQL this way? Why not

SELECT CategoryID, SubCategoryID, ReportedNumber
  FROM tblStatistics
 WHERE UnitCode = @unitCode
   AND FiscYear = @currYear
n8wrl
Correct you do not need to write dynamic sql just to pass parameters to your select statement inside of a stored procedure.
Joe Pitz
that's not my complete code, just an example to get across my error issue. i do have a good reason for making it dynamic. thanks!
Daria
+2  A: 

If we can assume that UnitCode is a VARCHAR field you'd have to add quotes around the @unitcode variable.

DECLARE @SQL varchar(600) 

SET @SQL =  
'SELECT     CategoryID, SubCategoryID, ReportedNumber 
 FROM    tblStatistics 
 WHERE   UnitCode = ''' + @unitCode + ''''
' AND   FiscYear = ' + @currYEAR 

EXEC (@SQL) 
Lieven
You're adding quotes, not parentheses... I've heard a million other people use the wrong word there before :P
Timothy Khouri
@Timothy Khouri - lol. Thank you for the correction.
Lieven