如何仅使用一个标识列插入到表中

时间:2022-11-22 22:44:26

(Came up with this question in the course of trying to answer this other one)

(在回答另一个问题的过程中提出了这个问题)

Consider the following MS-SQL table, called GroupTable:

考虑下面的MS-SQL表,称为GroupTable:

GroupID
-------
1  
2  
3  

where GroupID is the primary key and is an Identity column.

其中GroupID是主键,是标识列。

How do you insert a new row into the table (and hence generate a new ID) without using IDENTITY_INSERT ON?

如何在不使用IDENTITY_INSERT的情况下向表中插入新行(从而生成新ID) ?

Note that this:

注意:

INSERT INTO GroupTable() Values ()   

... wont work.

…不会工作。

edit: we're talking SQL 2005 or SQL 2008 here.

编辑:我们正在讨论SQL 2005或SQL 2008。

4 个解决方案

#1


108  

This should work:

这应该工作:

INSERT INTO GroupTable DEFAULT VALUES 

#2


17  

Here you go:

给你:

INSERT INTO GroupTable DEFAULT VALUES

#3


3  

It is possible to insert more than one row at a time.

一次插入多个行是可能的。

For e.g., to insert 30 rows. INSERT INTO GroupTable DEFAULT VALUES GO 30

例如,插入30行。插入到GroupTable默认值为30

This will insert 30 rows by incrementing the identity column each time.

这将通过每次递增标识列插入30行。

#4


0  

Can you try using a Sequence or something similar? Where you select from a Sequence and it will give you the next value in the sequence.

你能试着用一个序列或类似的东西吗?你从一个序列中选择它会给你序列中的下一个值。

#1


108  

This should work:

这应该工作:

INSERT INTO GroupTable DEFAULT VALUES 

#2


17  

Here you go:

给你:

INSERT INTO GroupTable DEFAULT VALUES

#3


3  

It is possible to insert more than one row at a time.

一次插入多个行是可能的。

For e.g., to insert 30 rows. INSERT INTO GroupTable DEFAULT VALUES GO 30

例如,插入30行。插入到GroupTable默认值为30

This will insert 30 rows by incrementing the identity column each time.

这将通过每次递增标识列插入30行。

#4


0  

Can you try using a Sequence or something similar? Where you select from a Sequence and it will give you the next value in the sequence.

你能试着用一个序列或类似的东西吗?你从一个序列中选择它会给你序列中的下一个值。