views:

60

answers:

3

In SQL Server, how can I insert data into a table that has just one column which is of identity type? Such as insert into the following table t. How can I write the insert statement?

CREATE TABLE t
(
    id INT IDENTITY(1, 1) PRIMARY KEY
)

Great thanks.

+3  A: 
INSERT T DEFAULT VALUES 

Or to insert multiple rows (up to 2048 at a time using the spt_values table)

SET IDENTITY_INSERT t ON
INSERT INTO t (id) 
SELECT Number + COALESCE(IDENT_CURRENT('t'),0) + 1
FROM master.dbo.spt_values
where type='p' and number < 2048
SET IDENTITY_INSERT t OFF
Martin Smith
A: 

Try:-

INSERT INTO t Values(NULL)
James Anderson
"An explicit value for the identity column in table 't' can only be specified when a column list is used and IDENTITY_INSERT is ON."
Martin Smith
+2  A: 

If you want to continue inserting identity values, then use

INSERT YourTable DEFAULT VALUES;

If you want to insert explicit values then you can write

SET IDENTITY_INSERT YourTable ON
INSERT INTO YourTable (id) VALUES (5);
SET IDENTITY_INSERT YourTable OFF
mdma
+1. I don't think `DEFAULT VALUES` can be used for multiple rows. (whereas inserting explicit values can easily cope with that)
Martin Smith