动态sql给出了语法错误。

时间:2014-01-29 20:09:31

标签: sql sql-server tsql

我正在执行以下sql。我收到一个语法错误('='附近的语法不正确) 查询执行正常,并在正常执行时给出正确的结果。无法理解。请仔细看看。

DECLARE @pvchMachineId VARCHAR(100)  = ''

DECLARE @pvchMake VARCHAR(100) = ''

DECLARE @sql NVARCHAR(1000)

SELECT @sql = ' SELECT TOP 20 x.intId, x.vchMachineId, x.AUDenom, x.intGroupId,

x.vchMake, x.vchModel, x.mCurrency

from dbo.Machine x

inner join
(select max(m1.AUDenom) as audenom, m1.vchMachineId

from dbo.Machine m1
left JOIN dbo.ImportedFile ife on m1.intImportedFileId = ife.intId
WHERE ife.dtFileDate >= ''1-1-2013'' AND ife.dtFileDate <= ''1-29-2014'' AND

--following two lines cause the error

(' + @pvchMake + '= ''0'' OR m1.vchMake = @pvchMake) AND

(' + @pvchMachineId +'= ''0'' OR m1.vchMachineId = @pvchMachineId)

group by vchMachineId) y

on x.AUDenom = y.audenom and x.vchMachineId = y.vchMachineId 
ORDER BY x.AUDenom DESC'

3 个答案:

答案 0 :(得分:2)

本声明:

'(' + @pvchMake + '= ''0'' OR m1.vchMake = @pvchMake)'

将输出,因为变量未被''以外的任何其他内容初始化:

(= '0' OR m1.vchMake = @pvchMake)

哪种语法不正确。

您应该使用:

'(''' + @pvchMake + '''= ''0'' OR m1.vchMake = @pvchMake)'

哪个会输出:

(''= '0' OR m1.vchMake = @pvchMake)

答案 1 :(得分:2)

将您的查询更新为以下

(@pvchMake = ''0'' OR m1.vchMake = @pvchMake) AND
(@pvchMachineId = ''0'' OR m1.vchMachineId = @pvchMachineId)

以后执行时只需将其作为参数传递给sp_executesql函数。

EXEC sp_executesql @sql
         ,N'@pvchMachineId VARCHAR(100), @pvchMake VARCHAR(100)'
         ,@pvchMachineId,@pvchMake

或更干净的

Declare @ParametersDefinition NVARCHAR(max) = N'@pvchMachineId VARCHAR(100), @pvchMake VARCHAR(100)'
EXEC sp_executesql @sql, @ParametersDefinition, @pvchMachineId,@pvchMake

最后,您不希望连接动态SQL语句,而是为SQL注入打开它。即使它是一个有效的选项,也应该不惜一切代价避免它。

答案 2 :(得分:0)

也许这有意义:

...

(''' + @pvchMake + '''= ''0'' OR m1.vchMake = ''' + @pvchMake +''') AND

(''' + @pvchMachineId +'''= ''0'' OR m1.vchMachineId = ''' + @pvchMachineId + ''')
...