我可以在多次插入时获取插入的 ID 吗?

Can I grab the inserted IDs when doing multiple inserts?

在我看来这听起来不太可能,但我想知道我是否可以做到:

INSERT INTO MyTable (Name)
VALUES ('First'),
('Second'),
('Third'),
('Fourth'),
('Fifth');

SELECT INSERTED Name, ID FROM TheAboveQuery 

其中 ID 是自动索引列?

澄清一下,我只想 select 新插入的行。

当然,您可以在 ID 字段上使用 IDENTITY 属性,然后在其上创建 CLUSTERED INDEX

ONLINE DEMO

create table MyTable (  ID int identity(1,1), 
                        [Name] varchar(64),
                        constraint [PK_MyTable] primary key clustered (ID asc) on [Primary]
                     )


--suppose this data already existed...
INSERT INTO MyTable (Name)
VALUES 
('First'),
('Second'),
('Third'),
('Fourth'),
('Fifth');


--now we insert some more... and then only return these rows
INSERT INTO MyTable (Name)
VALUES 
('Sixth'),
('Seventh')


select top (@@ROWCOUNT)
    ID, 
    Name 
from MyTable
order by ID desc

@@ROWCOUNT returns the number of rows affected by the last statement executed. You can always see this in the messages tab of SQL Server Management Studio. Thus, we are getting the number of rows inserted and combining it with TOP which limits the rows returned in a query to the specified number of rows (or percentage if you use [PERCENT]). It is important that you use ORDER BY when using TOP otherwise your results aren't guaranteed to be the same

来自我之前编辑的答案...

如果您试图查看插入了哪些值,那么我假设您以不同的方式插入它们,这通常使用 OUTPUT 子句处理,如果您尝试使用 TRIGGER插入后的这些记录等...需要更多信息。

从 SQL Server 2008 开始,您可以将 OUTPUT 子句与 INSERT 语句一起使用

DECLARE @T TABLE (ID INT, Name NVARCHAR(100))

INSERT INTO MyTable (Name)
OUTPUT INSERTED.ID, INSERTED.Name INTO @T
VALUES 
   ('First'),
   ('Second'),
   ('Third'),
   ('Fourth'),
   ('Fifth');

SELECT Name, ID FROM @T;

更新:如果table没有触发器

INSERT INTO MyTable (Name)
OUTPUT INSERTED.ID, INSERTED.Name
VALUES 
   ('First'),
   ('Second'),
   ('Third'),
   ('Fourth'),
   ('Fifth');