【问题标题】:SQL Server 2008 - insert into table with select script and a hardcoded valueSQL Server 2008 - 使用选择脚本和硬编码值插入表
【发布时间】:2012-03-12 23:35:00
【问题描述】:

我想在表格中插入以下信息:

Week                          NoTrans     Spend
02.01.12-08.01.12             11          520

我的脚本是:

DECLARE @Week VARCHAR(22)
DECLARE @Date1 DATETIME
DECLARE @Date2 DATETIME
DECLARE @Script VARCHAR(8000)
SET @date1 = '02 Jan 2012'
SET @date2 = '08 Jan 2012'
SET @Week = Convert(varchar(12), @date1, 104)+'-'+Convert(varchar(12), @date2, 104)

PRINT @Week

SET @Script = 'INSERT INTO table2 (WEEK, NoTrans, Spend)
SELECT '+ @WEEK +', Transactions, Spend
FROM table1 (NOLOCK)


EXEC @Script

Week 列来自 @Week 而不是 table1。

我收到以下错误消息:

消息 203,第 16 级,状态 2,第 20 行
名称 'INSERT INTO table2 (WEEK, Transactions, Spend) 选择 02.01.2012-08.01.2012,交易,花费 FROM table1 (NOLOCK)' 不是有效的标识符。

谢谢

【问题讨论】:

    标签: sql-server-2008 select insert-into


    【解决方案1】:

    尝试将最后一行更改为:

    EXEC sp_executesql @Script
    

    或者,不要费心创建@Script 和使用 EXEC,只需像这样运行查询:

    INSERT INTO table2 (WEEK, NoTrans, Spend)
    SELECT @WEEK, Transactions, Spend
    FROM table1 (NOLOCK)
    

    【讨论】:

      【解决方案2】:

      当您想使用EXECUTE 执行动态SQL 时,您需要使用括号:

       EXEC(@Script)
      

      您也可以按照另一个答案中的建议使用sp_executesql(它具有允许参数化查询的优势)。

      另外,我认为您需要为 WEEK 引用字符串:

      SET @Script = 'INSERT INTO table2 (WEEK, NoTrans, Spend)
      SELECT '''+ @WEEK +''', Transactions, Spend
      FROM table1'
      

      PS:请确保您了解使用 NOLOCK 的含义:

      http://blogs.msdn.com/b/davidlean/archive/2009/04/06/sql-server-nolock-hint-other-poor-ideas.aspx

      【讨论】:

      • 这个答案比我的要好... :) 是的,引用也是必要的,我没有发现
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      • 2014-10-05
      相关资源
      最近更新 更多