<\/script>')

TSQL "Invalid column name" error on sproc parameter value

here is 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!

+3
source share
4 answers

This is a good SQL injection vulnerability.

Start by overwriting this way using the binding options:

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
+8
source

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

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

- SQL

WHERE UnitCode = COB

COB . SQL ?

SELECT CategoryID, SubCategoryID, ReportedNumber
  FROM tblStatistics
 WHERE UnitCode = @unitCode
   AND FiscYear = @currYear
+3

, UnitCode VARCHAR, @unitcode.

DECLARE @SQL varchar(600) 

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

EXEC (@SQL) 
+3

Source: https://habr.com/ru/post/1737586/


All Articles