【问题标题】:SQL Server 2005 - Dynamic insert query issueSQL Server 2005 - 动态插入查询问题
【发布时间】:2012-05-14 10:31:06
【问题描述】:

我正在努力让这个语句运行

SET @SelectStatement = 'INSERT INTO [ArchiveProcessHistory] VALUES (' + @TableName + ',' + @TotalRowsSource +',' + @TotalRowsDestination + ',' + GetDate()') '

[我知道上述陈述有问题,我无法修复)

SET @FullStatement = @SelectStatement 

ArchiveProcessHistory 表结构为:

TableName - nvarch(5)
TotalRowsSource - integer
TotalRowsDestination - integer
DateofInsert - Date

运行 sp_executesql 时出现此错误

消息 102,级别 15,状态 1,过程 usp_ArchiveTable,第 39 行 ') ' 附近的语法不正确。

我该如何解决这个问题?

【问题讨论】:

    标签: sql-server-2005


    【解决方案1】:
    SET @SelectStatement = 'INSERT INTO [ArchiveProcessHistory] VALUES (' + @TableName + ',' + @TotalRowsSource +',' + @TotalRowsDestination + ',' + GetDate() + ') '
    

    getdate() 之后缺少一个+

    【讨论】:

      【解决方案2】:

      为避免潜在的 SQL 注入攻击,您可以改用 sp_executesql

      declare @SelectStatement nvarchar(max)
      
      set @SelectStatement = 
        'INSERT INTO [ArchiveProcessHistory] VALUES
          (@TableName, @TotalRowsSource, @TotalRowsDestination, GetDate())'
      
      exec sp_executesql @SelectStatement,
                         N'@TableName nvarchar(5), @TotalRowsSource int, @TotalRowsDestination int',
                         @TableName = '123', 
                         @TotalRowsSource = 4, 
                         @TotalRowsDestination = 5
      

      你也应该看看The Curse and Blessings of Dynamic SQL

      【讨论】:

      • +1 - 如果动态SQL是真正需要的(从问题中不清楚是否需要它),使用这样的参数化SQL
      • 但这些@TableName 是传递给存储过程的输入参数。
      • @ConradJagger 您不要在查询中将其用作表名。如果这样做,您应该使用quotename() 将表名连接到@SelectStatement
      【解决方案3】:

      在作为函数的插入语句中,使用 current_timestamp 代替 GetDate()。

      SET @SelectStatement = 'INSERT INTO [ArchiveProcessHistory] VALUES (' + @TableName + ','   + @TotalRowsSource +',' + @TotalRowsDestination + ',' + current_timestamp + ') '
      

      【讨论】:

      • 这失败了,因为 TableName 是 VARCHAR ......当我运行上面的语句时失败...... varchar 错误
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 2011-04-01
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-10
      相关资源
      最近更新 更多