Inserting one record:
I only do this to insert a row into a table with a non auto-incremented primary key:
DECLARE @myKey int SET @myKey = (SELECT ISNULL(MAX(primaryKey),0) FROM dbo.myTable) INSERT INTO dbo.myTABLE (primaryKey, field1, fiels2) VALUES (@myKey + 1, value1, value2)
Inserting multiple records:
In another situation, I needed to duplicate multiple records in a table. For this, I used an INSERT from the result of a SELECT. My intention was to duplicate some records from myTable, that meet a specific condition. But I needed to figure out how to duplicate records in a table with a unique PRIMARY KEY, without repeating an ID. Here's how I solved it:
DECLARE @myKey int SET @myKey = (SELECT ISNULL(MAX(primaryKey),0) FROM dbo.myTable) INSERT INTO dbo.myTABLE (primaryKey, field1, fiels2) SELECT (primaryKey + @myKey, value1, value2) FROM dbo.myTable WHERE value2 = especific_Condition
There were some gaps in the IDs, but I enforce uniqueness PRIMARY KEY.
IDENTITYcolumn on the table? If so, what precise problem are you having that is not discussed in the documentation or the many questions on this site about using them? In a comment below you mention an error but you haven't said exactly what it is. Ideally, please show yourCREATE TABLEscript, yourINSERTstatement, and the resulting error message.SET IDENTITY_INSERT sometableWithIdentity ONfrom stackoverflow.com/a/7063527/1548275 is a clear approach to problem as I see it.