简体   繁体   中英

SQL Server error: “Incorrect syntax near 'xyz'”

I am getting this error when trying to insert values into a table with a stored procedure in SQL Server 2016. I am using dynamic SQL:

SET @InsertIntoTable = 'INSERT INTO ' + @TableName + 
          'VALUES (' + @Param1 + 
          ',' + @Param2 +
          ',' + @Param3 +
          ',' + @Param4 +
          ',' + @Param5 +
          ',' + @Param6 +
          ',' + @Param7 + ')'

The error occurs when I want to insert a value in @Param3, in which I am passing in a hexadecimal string (eg the string "24A673C87B11AE1D8F50765E86270FA0546F241F499868").

The error says that there is an incorrect syntax at "A673C87B11AE1D8F50765E86270FA0546F241F499868" (this is exactly from the error for my example provided above, it is only a substring of the original string, not the entire string). I am passing in hexadecimal strings for @Param3, @Param4 and @Param5

Ideally you should use sp_executesql but to fix the problem you have you should do the following:

SET @InsertIntoTable = 'INSERT INTO ' + @TableName + 
          ' VALUES (''' + @Param1   --<-- space before Values 
             + ''', ''' + @Param2 
             + ''', ''' + @Param3 
             + ''', ''' + @Param4 
             + ''', ''' + @Param5
             + ''', ''' + @Param6
             + ''', ''' + @Param7 
             + ''')'

To use sp_executesql with the parameterised query you would do the following, it also protects you against sql-injection attacks.

Declare @Sql NVARCHAR(MAX);

SET @sql = N' INSERT INTO ' + QUOTENAME(@TableName) 
         + N' VALUES (    @Param1 
                        , @Param2 
                        , @Param3 
                        , @Param4 
                        , @Param5
                        , @Param6
                        , @Param7);'

 Exec sp_executesql   @sql 
                    , N'@Param1 [datatype] , @Param2 [datatype], @Param3 [datatype]....'
                    , @Param1 
                    , @Param2 
                    , @Param3 
                    , @Param4 
                    , @Param5
                    , @Param6
                    , @Param7;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM