“动态sql查询”附近的语法不正确

时间:2015-07-26 17:40:27

标签: sql-server stored-procedures dynamic-sql

/ *当我在sql server中执行此过程时,它正确执行,但是当我通过编码执行时,我得到此错误"在set"附近的语法不正确     提前致谢* /

ALTER PROCEDURE [dbo].[updateCitationTrust]
@tblName varchar(50),
@updatedTableName varchar(50)

AS
DECLARE @sql NVARCHAR(4000)
Declare @ParamDefinition AS NVarchar(2000) 
BEGIN
 --BEGIN TRANSACTION 


 set @sql='Update '+@updatedTableName+ ' set [Citation Flow]=m2.[Citation Flow],'+
    ' [Trust Flow]=m2.[Trust Flow]'+
    ' FROM '+ @updatedTableName+ ' m1 '+
    ' INNER JOIN  '+ @tblName+' m2'+
    ' on m1.[Linking Domain]=m2.[Item]'

 Set @ParamDefinition =      '@tblName varchar(50),
                @updatedTableName varchar(50)'



 Execute sp_Executesql     @sql, 
                @ParamDefinition, 
                @tblName,
                @updatedTableName


    If @@ERROR <> 0 GoTo ErrorHandler 
    Set NoCount OFF
    Return(0)

ErrorHandler:
    Return(@@ERROR)
END 

1 个答案:

答案 0 :(得分:0)

如果对象名称作为参数值传递,而不是对常规标识符(https://msdn.microsoft.com/en-us/library/ms175874.aspx?f=255&MSPPError=-2147217396)的规则进行确认,则需要引用。使用QUOTENAME功能。这也将降低SQL注入的风险。

ALTER PROCEDURE [dbo].[updateCitationTrust]
@tblName varchar(50),
@updatedTableName varchar(50)

AS
DECLARE @sql NVARCHAR(4000)
Declare @ParamDefinition AS NVarchar(2000) 
BEGIN
 --BEGIN TRANSACTION 


 set @sql='Update '+QUOTENAME(@updatedTableName)+ ' set [Citation Flow]=m2.[Citation Flow],'+
    ' [Trust Flow]=m2.[Trust Flow]'+
    ' FROM '+ QUOTENAME(@updatedTableName)+ ' m1 '+
    ' INNER JOIN  '+ QUOTENAME(@tblName)+' m2'+
    ' on m1.[Linking Domain]=m2.[Item]'

 Set @ParamDefinition =      '@tblName varchar(50),
                @updatedTableName varchar(50)'



 Execute sp_Executesql     @sql, 
                @ParamDefinition, 
                @tblName,
                @updatedTableName


    If @@ERROR <> 0 GoTo ErrorHandler 
    Set NoCount OFF
    Return(0)

ErrorHandler:
    Return(@@ERROR)
END