views:

199

answers:

5

A colleague asked me, if you have a table in SQL Server with only an auto-increment column, how do you insert a new row into that table?

INSERT INTO MyTable() VALUES()

...doesn't work.

As for why... I'm not really sure. But I found the question kind of compelling.

+1  A: 

Apparently this works:

INSERT INTO MyTable DEFAULT VALUES

(Just discovered it after I hit Ask Question. Sorry!)

Scott Whitlock
A: 
set identity_insert MyTable ON

insert MyTable(MyIdentColumn) values(42)

set identity_insert MyTable OFF
Scott Ivey
Interesting approach. It might work better if you replace 42 with something that calculates the next auto-increment value, like MAX(id) + 1.
Scott Whitlock
calculating the max+1 would defeat the purpose of inserting an explicit value into an identity column. The 42 was just there as an example - you'd plug whatever value you were trying to insert there. If you just wanted the max, you wouldn't use my example at all.
Scott Ivey
A: 

Use the IDENTITY_INSERT Setting:

SET IDENTITY_INSERT MyTable ON INSERT INTO MyTable (AutoIncrementColumnName, OtherColumnNames...) VALUES (9999, OtherData...) SET IDENTITY_INSERT MyTable OFF

Make sure you insert a value that isn't in the key already.

Michael Bray
+5  A: 
insert into mytable default values
zinglon
+2  A: 

use default values, works also with defaults

create table #test (id int identity, Somedate datetime default getdate())


insert #test default values

select * from #test

id Somedate

1 2009-06-30 16:04:03.307

SQLMenace