在 INSERT 语句中使用带有 from_table_name 的 OUTPUT INTO
Using OUTPUT INTO with from_table_name in an INSERT statement
Microsoft's OUTPUT Clause documentation 表示您可以在 OUTPUT 子句的列名中使用 from_table_name。
有两个例子:
- Using OUTPUT INTO with from_table_name in an UPDATE statement
- Using OUTPUT INTO with from_table_name in a DELETE statement
是否也可以在 INSERT 语句中使用它?
INSERT INTO T ( [Name] )
OUTPUT S.Code, inserted.Id INTO @TMP -- The multi-part identifier "S.Code" could not be bound.
SELECT [Name] FROM S;
使用 table 个变量的失败示例
-- A table to insert into.
DECLARE @Item TABLE (
[Id] [int] IDENTITY(1,1),
[Name] varchar(100)
);
-- A table variable to store inserted Ids and related Codes
DECLARE @T TABLE (
Code varchar(10),
ItemId int
);
-- Insert some new items
WITH S ([Name], Code) AS (
SELECT 'First', 'foo'
UNION ALL SELECT 'Second', 'bar'
-- Etc.
)
INSERT INTO @Item ( [Name] )
OUTPUT S.Code, inserted.Id INTO @T -- The multi-part identifier "S.Code" could not be bound.
SELECT [Name] FROM S;
不,因为 INSERT 没有 FROM;它有一组由 VALUES 关键字或查询准备的值(即使该查询有 FROM,您应该认为它已经 运行 并由插入完成的时间;不再有 s.code
)
如果您想从驱动插入的 table 中输出某些内容,您需要使用从不匹配任何记录的合并语句(因此它只是插入),或者可能插入所有数据到@tmp 然后从@tmp 插入到真正的 table - @tmp 因此仍然是插入的行的记录,只是它是为了驱动插入而创建的而不是它的结果(注意它不会包含计算列)
Microsoft's OUTPUT Clause documentation 表示您可以在 OUTPUT 子句的列名中使用 from_table_name。
有两个例子:
- Using OUTPUT INTO with from_table_name in an UPDATE statement
- Using OUTPUT INTO with from_table_name in a DELETE statement
是否也可以在 INSERT 语句中使用它?
INSERT INTO T ( [Name] )
OUTPUT S.Code, inserted.Id INTO @TMP -- The multi-part identifier "S.Code" could not be bound.
SELECT [Name] FROM S;
使用 table 个变量的失败示例
-- A table to insert into.
DECLARE @Item TABLE (
[Id] [int] IDENTITY(1,1),
[Name] varchar(100)
);
-- A table variable to store inserted Ids and related Codes
DECLARE @T TABLE (
Code varchar(10),
ItemId int
);
-- Insert some new items
WITH S ([Name], Code) AS (
SELECT 'First', 'foo'
UNION ALL SELECT 'Second', 'bar'
-- Etc.
)
INSERT INTO @Item ( [Name] )
OUTPUT S.Code, inserted.Id INTO @T -- The multi-part identifier "S.Code" could not be bound.
SELECT [Name] FROM S;
不,因为 INSERT 没有 FROM;它有一组由 VALUES 关键字或查询准备的值(即使该查询有 FROM,您应该认为它已经 运行 并由插入完成的时间;不再有 s.code
)
如果您想从驱动插入的 table 中输出某些内容,您需要使用从不匹配任何记录的合并语句(因此它只是插入),或者可能插入所有数据到@tmp 然后从@tmp 插入到真正的 table - @tmp 因此仍然是插入的行的记录,只是它是为了驱动插入而创建的而不是它的结果(注意它不会包含计算列)