91

(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
  • 13,221
  • 9
  • 64
  • 84
codeulike
  • 22,514
  • 29
  • 120
  • 167

5 Answers5

138

This should work:

INSERT INTO GroupTable DEFAULT VALUES 
DJ.
  • 16,045
  • 3
  • 42
  • 46
17

Here you go:

INSERT INTO GroupTable DEFAULT VALUES
tofi9
  • 5,775
  • 4
  • 29
  • 50
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.

RMK
  • 29
  • 1
  • Not sure about SQL 2008, but in 2008R2 this does not work (I get the generic error "Invalid syntax near 'GO'") – Elaskanator Jun 13 '18 at 13:47
  • 1
    @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 – J.D. Dec 17 '22 at 14:52
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
  • 18,705
  • 13
  • 53
  • 68
  • 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
-1

This will work actually--

insert into TABLE default values

  • 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](/help/how-to-answer). – Community May 15 '22 at 00:31