2012-03-27 40 views
2

我想我可能會誤解爲什麼使用with命令。但是,任何人都可以看到我做錯了什麼。 我想做一個查詢,並使用結果的兩件事情。首先,我想使用這些值將一些插入到另一個表中。然後我想將結果顯示給用戶。TSQL多用於定義WITH表

所以我有這樣的事情。

With temp as (
Select * from Table1 
) 
INSERT INTO Table2 (table1_id) select id from temp 
SELECT * from temp 

我也得到

Error: Invalid object name 'temp'. SQLState: S0002 ErrorCode: 208

這不是什麼用的命令是?

回答

5

MSDN

A common table expression (CTE) can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement.

由於insert語句和select聲明是兩個不同的語句時,CTE是僅適用於insert

作爲替代方案,你可以考慮使用OUTPUT clause

WITH temp AS (
    SELECT * FROM Table1 
) 
INSERT INTO Table2 (table1_id) 
OUTPUT inserted.id 
SELECT id FROM temp 
0

有另一種方式來實現你想要做什麼。嘗試如下。

Select * into #temp_table 
from Table1 

INSERT INTO Table2 (table1_id) select id from #temp_table 
SELECT * from #temp_table