87

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

Luke Girvin
  • 12,672
  • 8
  • 57
  • 79
codeulike
  • 20,946
  • 27
  • 113
  • 161

4 Answers4

129

This should work:

INSERT INTO GroupTable DEFAULT VALUES 
DJ.
  • 15,477
  • 3
  • 39
  • 45
17

Here you go:

INSERT INTO GroupTable DEFAULT VALUES
tofi9
  • 5,495
  • 4
  • 27
  • 48
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

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

RMK
  • 31
  • 1
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.

Mike Pone
  • 17,050
  • 12
  • 49
  • 63
  • I think he's talking about Oracle DB – codeulike May 11 '09 at 22:26
  • 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 May 12 '09 at 15:48
  • 3
    SQL Server 2012 has [SEQUENCE](http://msdn.microsoft.com/en-us/library/ff878091.aspx)s. – Nick Chammas May 24 '12 at 21:56