0

I want to insert into a table the following information:

Week                          NoTrans     Spend
02.01.12-08.01.12             11          520

The script I have is:

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

The Week column comes from @Week not table1.

I'm getting the following error message:

Msg 203, Level 16, State 2, Line 20
The name 'INSERT INTO table2 (WEEK, Transactions, Spend) SELECT 02.01.2012-08.01.2012, Transactions, Spend FROM table1 (NOLOCK)' is not a valid identifier.

Thanks

4

2 に答える 2

3

Try changing the last line to:

EXEC sp_executesql @Script

Or alternatively, don't bother with creating @Script and using EXEC, just run the query like this:

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 に答える