93

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

Consider the following MS-SQL table, called GroupTable:

GroupID
-------
1  
2  
3  

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

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

Note that this:

INSERT INTO GroupTable() Values ()   

... won't work.

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

5 Answers 5

142

This should work:

INSERT INTO GroupTable DEFAULT VALUES 
Sign up to request clarification or add additional context in comments.

4 Comments

I can't get this to work with Visual Studio 2008/SQL Express 2005. Any ideas? Same table layout, one column, primary key, identity(1,1).
I'm using SQL 2008 R2, no joy for me either!
Works for me on SQL Server 2008 Express.
@RomanPekar, in SqlServer 2008 and later it is possible with merge operator. E.g. merge into TableName using (values (1), (2), (3)) s(n) on 1=0 when not matched then insert default values;
17

Here you go:

INSERT INTO GroupTable DEFAULT VALUES

Comments

2

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

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

2 Comments

Not sure about SQL 2008, but in 2008R2 this does not work (I get the generic error "Invalid syntax near 'GO'")
@Elaskanator GO has to be on its own line. Looks like RMK just formatted his example improperly, by forgetting to put it on a new line. GO is not a T-SQL keyword, rather it's a special command recognized by SSMS on how to process the preceding T-SQL
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.

3 Comments

I think he's talking about Oracle DB
I know sequences exist in Oracle and wasn't sure what (if any) comparable thing existed in SQL Server. That is why I suffixed it with "or something similar" and then gave a definistion of a Sequence for reference.
SQL Server 2012 has SEQUENCEs.
-1

This will work actually--

insert into TABLE default values

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.