13

我有一个单列表,这是一个自动生成的标识

create table SingleIdTable (
   id int identity(1,1) not null
)

我可以使用自动生成的 id 插入一行:

insert into SingleIdTable default values

我想插入许多行并使用输出语法来获取它们的 ID,例如:

insert into SingleIdTable
output inserted.Id into @TableOfIds
    select (default values) from SomeOtherTable where Attribute is null

目的是使用自动生成的 idSingleIdTable为每行插入一行,SomeOtherTable其中为 null。Attribute以上不起作用,但我该怎么做。我注意到,如果我的表不止一列,我可以这样做,但我不能选择空行,这是我真正想要做的。

我无法更改 的定义SomeOtherTable

4

2 回答 2

23

如果 SQL Server 2008+ 你可以使用MERGE这个。下面的示例语法。

MERGE INTO SingleIdTable
USING (SELECT *
       FROM   SomeOtherTable
       WHERE  Attribute IS NULL) T
ON 1 = 0
WHEN NOT MATCHED THEN
  INSERT
  DEFAULT VALUES
OUTPUT INSERTED.id; 

我不确定这个单列表有什么实际用途?

于 2012-10-12T16:52:32.717 回答
1

you did not specify which version of SQL Server you are on. If you happen to be on SQL 2012 you probably can replace you SingleIdTable with a sequence: http://msdn.microsoft.com/en-us/library/ff878091.aspx

于 2012-10-12T17:13:48.803 回答