0

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

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列来自@Weeknot table1。

我收到以下错误消息:

消息 203,级别 16,状态 2,第 20 行
名称“INSERT INTO table2 (WEEK, Transactions, Spend) SELECT 02.01.2012-08.01.2012, Transactions, Spend FROM table1 (NOLOCK)”不是有效标识符。

谢谢

4

2 回答 2

3

尝试将最后一行更改为:

EXEC sp_executesql @Script

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

INSERT INTO table2 (WEEK, NoTrans, Spend)
SELECT @WEEK, Transactions, Spend
FROM table1 (NOLOCK)
于 2012-03-12T23:40:42.793 回答
1

当您想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

于 2012-03-12T23:56:53.693 回答