如何使用先前查询的结果插入表中

时间:2013-04-19 07:29:13

标签: tsql sql-server-2008-r2

早上好。

我正在使用上一个查询的结果填充多对多表格,如下所示......

WITH Temp AS
(
    SELECT      UserID, Result 
    FROM        <Master_Table>
    WHERE       UserID IN (SELECT Name FROM Users)
)   
INSERT INTO UserDecisions 
    (User_Id, Decision_Id)
    VALUES
    (
        (SELECT Id FROM Users WHERE Temp.UserID = Users.Name),
        (SELECT Id FROM Decisions WHERE Temp.Result = Decisions.Name)
    )

执行时,我得到如下错误。

Msg 4104, Level 16, State 1, Line 22
The multi-part identifier "Temp.UserID" could not be bound.
Msg 4104, Level 16, State 1, Line 23
The multi-part identifier "Temp.Result" could not be bound.

你会如何解决这个问题? Temp子查询是否需要是临时表?

1 个答案:

答案 0 :(得分:3)

您需要将其编写为SELECT而不是VALUES子句:

WITH Temp AS
(
    SELECT      UserID, Result 
    FROM        <Master_Table>
    WHERE       UserID IN (SELECT Name FROM Users)
)   
INSERT INTO UserDecisions 
    (User_Id, Decision_Id)
    SELECT u.Id,d.Id
    FROM Temp t
    INNER JOIN Users u ON t.UserID = u.Name
    INNER JOIN Decisions d ON t.Result = d.Name