首页 > 解决方案 > 使用 from 子句插入到输出表中

问题描述

我正在尝试复制表中的一些行,并更改了几个值,并且我还需要存储一个旧的(将丢失的)ID 以便稍后进行进一步处理。我正在尝试使用输出子句来存储该信息,但 SQL Server 抛出以下错误:

Msg 4104 <...> The multi-part identifier could not be bound.

这是我正在复制数据的表(稍作修改以减少列数):

Create Table Elements
(
    id              int Identity(0,1)   not null, --PK
    name            varchar(50)         not null,
    modelID         int                 not null, --FK

    constraint PK_Elements primary key (id)
);

这是我的查询:

declare @outputTable table 
(
    oldElementID    int,
    id              int,
    name            varchar(50),
    modelID         bigint
);

Insert into Elements
(name, modelID)
Output e.id as oldElementID, 
    Inserted.id,
    Inserted.name,
    Inserted.modelID into @outputTable
select e.name, @newModelID
from Elements as e
where e.modelID = @oldModelID

注意:@oldModelID 和@newModelID 是先前声明和设置的。

我不确定我的逻辑是否错误,我必须采取不同的方法(但我确信可以这样做)。或者,如果我只是有一个我无法完全解决的错误。

任何帮助,将不胜感激。

谢谢!

标签: sqlsql-server

解决方案


我重新创建了这样的问题:

CREATE TABLE #a (a INT, b INT)

INSERT INTO #a (a,b) VALUES (42, 43)

INSERT INTO #a (a, b)
OUTPUT a.a, a.b, inserted.a, inserted.b
SELECT a.b, a.a
FROM #a a

插入操作产生消息:

Msg 4104, Level 16, State 1, Line 7
The multi-part identifier "a.a" could not be bound.
Msg 4104, Level 16, State 1, Line 7
The multi-part identifier "a.b" could not be bound.

那是因为 INSERT 命令看不到我在 select 命令中使用的别名“a”。


推荐阅读