views:

912

answers:

3

(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 ()

... wont work.

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

A: 

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.

Mike Pone
-1 What's a sequence? Never heard of it.
Andomar
I think he's talking about Oracle DB
codeulike
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.
Mike Pone
+16  A: 

This should work:

INSERT INTO GroupTable DEFAULT VALUES
DJ
It better work or I'll remove my upvote! :)
Andomar
sounds like this works on SQL 2005/2008, thanks.
codeulike
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).
Thomas Sandberg
+9  A: 

Here you go:

INSERT INTO GroupTable DEFAULT VALUES
taoufik
Does this work in SQL 2005/2008? I dont have it infront of me to check ...
codeulike
It does work, and DJ gave the first correct answer.
Andomar