为多个插入选择多个标识值以及未插入表中的列

时间:2012-02-17 13:42:48

标签: sql sql-server sql-server-2005 tsql

我只在TempId表中插入一列,即select语句中的名称 如何获得标识列的相应orderId。

INSERT INTO tempId 
output inserted.ID 
Select name FROM (
select 'erty' as name, 1 as orderid union 
select 'rth' as name, 2 as orderid union 
select 'yt' as name, 3 as orderid union 
select '345' as name, 4 as orderid union 
select 'rtyu' as name, 5 as orderid union 
select 'uio' as name, 6 as orderid union 
select 'yu' as name, 7 as orderid union 
select 'xzf' as name, 8 as orderid
) as a 

PS注意:带有union的SELECT仅用于示例查询。理想情况下,我会从另一张桌子上得到东西。

3 个答案:

答案 0 :(得分:3)

您可以使用OUTPUT子句将以后需要使用的id和任何其他字段放在表变量或临时表中

DECLARE @MyTableVar table( ID int, orderid int);
INSERT mytable (field1, orderID)
    OUTPUT INSERTED.ID, INSERTED.OrderID
        INTO @MyTableVar
SELECT FIELD2, orderid FROM Myothertable

现在,您可以在@MyTableVar中使用数据来插入子表或您想要执行的其他工作。

答案 1 :(得分:0)

只需安排专栏:

create table #tempID( id int, name varchar(50))

INSERT INTO #tempID (name, id)
output inserted.ID 
Select name, orderid FROM (
select 'erty' as name, 1 as orderid union 
select 'rth' as name, 2 as orderid union 
select 'yt' as name, 3 as orderid union 
select '345' as name, 4 as orderid union 
select 'rtyu' as name, 5 as orderid union 
select 'uio' as name, 6 as orderid union 
select 'yu' as name, 7 as orderid union 
select 'xzf' as name, 8 as orderid
) as a 

答案 2 :(得分:-4)

这是直接插入值的示例。如果没有触发器,您可以获得@@ IDENTITY。

  insert into [FTSwordDef] ([word]) values ('value') 
  select scope_identity();

Scope_identity(和邪恶的@@)只会返回最后一个iden。如果要插入多行,我认为您需要在SP中循环并构建iden列表。 Iden是由插入创建的,在我所知的插入中不可用。

如果你在插入物上持有一个标签锁并检索最后一个标识并插入了多少行,那么理论上插入物得到最后的x个inden值。如果您的插入已经排序,您将知道哪一行与哪一行有关。