I'm having newsequentialid() learning problems in sql server management studio. Create a table with a uniqueidentifier column 'UniqueID', and set the default to newsequentialid().
Step 1. saving the design:
'Table_1' table
- Error validating the default for column 'UniqueID'.
Save it anyway.
Step 2. view the sql:
CREATE TABLE [dbo].[Table_1](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[UniqueID] [uniqueidentifier] NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Table_1] ADD CONSTRAINT [DF_Table_1_UniqueID] DEFAULT (newsequentialid()) FOR [UniqueID]
GO
Looks reasonable.
Step 3. add some rows:
1 test 72b48f77-0e26-de11-acd4-001bfc39ff92
2 test2 92f0fc8f-0e26-de11-acd4-001bfc39ff92
3 test3 122aa19b-0e26-de11-acd4-001bfc39ff92
They don't look very sequential. ??
Edit: I have gotten it to work somewhat if the inserts are all done at once, then the unique id is sequential. On later inserts, sql server seems to forget the last sequential id, and starts a new sequence.
Running this in ssms results in squential guids:
insert into Table_1 (Name) values('test13a');
insert into Table_1 (Name) values('test14a');
insert into Table_1 (Name) values('test15a');
insert into Table_1 (Name) values('test16a');
insert into Table_1 (Name) values('test17a');
newsequentialid is primarily to solve the issue of page fragmentation when your table is clustered by a uniqueidentifier. Your table is clustered by an integer column. I set up two test tables, one where the newsequentialid column is the primary key and one where it is not (like yours), and in the primary key the GUIDs were always sequential. In the other, they were not.
I do not know the internals/technical reasons why it behaves that way, but it seems clear that newsequentialid() is only truly sequential when your table is clustered by it. Otherwise, it seems to behave similarly to newid() / RowGuid.
Also, I'm curious as to why you would want to use newsequentialid() when you don't have to. It has many downsides which newid() does not, and none of the benefits - the biggest being that newid() is not practically predictable, whereas newsequentialid() is. If you are not worried about fragmentation, what's the point?
Those values are actually "sequential" as per the definition of NEWSEQUENTIALID():
Creates a GUID that is greater than any GUID previously generated by
this function on a specified computer since Windows was started.
It doesn't say there can't be any gaps in the GUIDs, it's just that any new GUID should be greater than the previous one.
Try this:
create table #test(id int, txt varchar(50), gid uniqueidentifier)
insert into #test
select 1 ,'test','72b48f77-0e26-de11-acd4-001bfc39ff92'
union select 2, 'test2', '92f0fc8f-0e26-de11-acd4-001bfc39ff92'
union select 3, 'test3', '122aa19b-0e26-de11-acd4-001bfc39ff92'
select * from #test
order by gid asc
As you can see, the records are ordered 1, 2, 3 which is as expected.
THEY ARE SEQUENTIAL!
1 test 72b48f77-0e26-de11-acd4-001bfc39ff92
2 test2 92f0fc8f-0e26-de11-acd4-001bfc39ff92
3 test3 122aa19b-0e26-de11-acd4-001bfc39ff92
77 < 8f < 9b !!! You have to see the highest value byets, not the lowest (from right to left)
I'm not familiar with newsequentialid(), for uniqueidentifier types I call newid().
There definitely can be gaps in NewSequentialId() sequences - I've found the following causes gaps:
As soon as another call is made by another table needing a NewSequentialId()
Failed inserts
Rollbacks
(2 and 3 are similar to identity() in this respect)
For example, given 2 tables using NewSequentialId()
create table XXX(someGuid uniqueidentifier DEFAULT NEWSEQUENTIALID(), x INT)
create table YYY(someGuid uniqueidentifier DEFAULT NEWSEQUENTIALID(), y DateTime)
GO
insert into XXX(x) values(1)
insert into XXX(x) values(2)
insert into XXX(x) values(3)
GO
insert into YYY(y) values(current_timestamp)
insert into YYY(y) values(current_timestamp)
insert into YYY(y) values(current_timestamp)
GO
insert into XXX(x) values(4)
insert into XXX(x) values(5)
insert into XXX(x) values(6)
GO
SELECT * FROM XXX
6A6E85CB-CCA3-E111-9E8E-005056C00008 1
6B6E85CB-CCA3-E111-9E8E-005056C00008 2
6C6E85CB-CCA3-E111-9E8E-005056C00008 3
**CCEA7AF2-CCA3-E111-9E8E-005056C00008 4** Gap here because we 'switched' to y
CDEA7AF2-CCA3-E111-9E8E-005056C00008 5
CEEA7AF2-CCA3-E111-9E8E-005056C00008 6
SELECT * FROM YYY
8F9438E1-CCA3-E111-9E8E-005056C00008 2012-05-22 07:13:35.503
909438E1-CCA3-E111-9E8E-005056C00008 2012-05-22 07:13:41.210
919438E1-CCA3-E111-9E8E-005056C00008 2012-05-22 07:13:41.220
Also, NewSequentialId()s aren't returned to the sequence in the case of a failed insert, e.g.
insert into XXX(x) values(1)
insert into XXX(x) values(2)
BEGIN TRAN
insert into XXX(x) values(3)
insert into XXX(x) values(4)
ROLLBACK TRAN
insert into XXX(x) values(5)
insert into XXX(x) values(6)
GO
686EFE5B-CDA3-E111-9E8E-005056C00008
696EFE5B-CDA3-E111-9E8E-005056C00008
6C6EFE5B-CDA3-E111-9E8E-005056C00008
6D6EFE5B-CDA3-E111-9E8E-005056C00008
i.e. a Gap of 2 Guids rolled back
and
insert into XXX(x) values(1)
insert into XXX(x) values(2)
insert into XXX(x) values(3)
GO
insert into XXX(x) values(99999999999999) -- overflow
GO
insert into XXX(x) values(4)
insert into XXX(x) values(5)
insert into XXX(x) values(6)
go
select * from xxx
AC613611-CFA3-E111-9E8E-005056C00008 1
AD613611-CFA3-E111-9E8E-005056C00008 2
AE613611-CFA3-E111-9E8E-005056C00008 3
**B0613611-CFA3-E111-9E8E-005056C00008 4** Gap of 1 - overflow failure
B1613611-CFA3-E111-9E8E-005056C00008 5
B2613611-CFA3-E111-9E8E-005056C00008 6
NEWSEQUENTIALGUID (as every guid generated in a way that warrant their sequence) includes a part of the Guid calculated via a time stamp. So if you run the inserts at different time you'll see some gaps.
But the important part is that the Guid are "ordered" in a way that do not cause page splits (if the Guid is used in a index) and this is what happens when using the new sequential guid.
Related
I'm having newsequentialid() learning problems in sql server management studio. Create a table with a uniqueidentifier column 'UniqueID', and set the default to newsequentialid().
Step 1. saving the design:
'Table_1' table
- Error validating the default for column 'UniqueID'.
Save it anyway.
Step 2. view the sql:
CREATE TABLE [dbo].[Table_1](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[UniqueID] [uniqueidentifier] NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Table_1] ADD CONSTRAINT [DF_Table_1_UniqueID] DEFAULT (newsequentialid()) FOR [UniqueID]
GO
Looks reasonable.
Step 3. add some rows:
1 test 72b48f77-0e26-de11-acd4-001bfc39ff92
2 test2 92f0fc8f-0e26-de11-acd4-001bfc39ff92
3 test3 122aa19b-0e26-de11-acd4-001bfc39ff92
They don't look very sequential. ??
Edit: I have gotten it to work somewhat if the inserts are all done at once, then the unique id is sequential. On later inserts, sql server seems to forget the last sequential id, and starts a new sequence.
Running this in ssms results in squential guids:
insert into Table_1 (Name) values('test13a');
insert into Table_1 (Name) values('test14a');
insert into Table_1 (Name) values('test15a');
insert into Table_1 (Name) values('test16a');
insert into Table_1 (Name) values('test17a');
newsequentialid is primarily to solve the issue of page fragmentation when your table is clustered by a uniqueidentifier. Your table is clustered by an integer column. I set up two test tables, one where the newsequentialid column is the primary key and one where it is not (like yours), and in the primary key the GUIDs were always sequential. In the other, they were not.
I do not know the internals/technical reasons why it behaves that way, but it seems clear that newsequentialid() is only truly sequential when your table is clustered by it. Otherwise, it seems to behave similarly to newid() / RowGuid.
Also, I'm curious as to why you would want to use newsequentialid() when you don't have to. It has many downsides which newid() does not, and none of the benefits - the biggest being that newid() is not practically predictable, whereas newsequentialid() is. If you are not worried about fragmentation, what's the point?
Those values are actually "sequential" as per the definition of NEWSEQUENTIALID():
Creates a GUID that is greater than any GUID previously generated by
this function on a specified computer since Windows was started.
It doesn't say there can't be any gaps in the GUIDs, it's just that any new GUID should be greater than the previous one.
Try this:
create table #test(id int, txt varchar(50), gid uniqueidentifier)
insert into #test
select 1 ,'test','72b48f77-0e26-de11-acd4-001bfc39ff92'
union select 2, 'test2', '92f0fc8f-0e26-de11-acd4-001bfc39ff92'
union select 3, 'test3', '122aa19b-0e26-de11-acd4-001bfc39ff92'
select * from #test
order by gid asc
As you can see, the records are ordered 1, 2, 3 which is as expected.
THEY ARE SEQUENTIAL!
1 test 72b48f77-0e26-de11-acd4-001bfc39ff92
2 test2 92f0fc8f-0e26-de11-acd4-001bfc39ff92
3 test3 122aa19b-0e26-de11-acd4-001bfc39ff92
77 < 8f < 9b !!! You have to see the highest value byets, not the lowest (from right to left)
I'm not familiar with newsequentialid(), for uniqueidentifier types I call newid().
There definitely can be gaps in NewSequentialId() sequences - I've found the following causes gaps:
As soon as another call is made by another table needing a NewSequentialId()
Failed inserts
Rollbacks
(2 and 3 are similar to identity() in this respect)
For example, given 2 tables using NewSequentialId()
create table XXX(someGuid uniqueidentifier DEFAULT NEWSEQUENTIALID(), x INT)
create table YYY(someGuid uniqueidentifier DEFAULT NEWSEQUENTIALID(), y DateTime)
GO
insert into XXX(x) values(1)
insert into XXX(x) values(2)
insert into XXX(x) values(3)
GO
insert into YYY(y) values(current_timestamp)
insert into YYY(y) values(current_timestamp)
insert into YYY(y) values(current_timestamp)
GO
insert into XXX(x) values(4)
insert into XXX(x) values(5)
insert into XXX(x) values(6)
GO
SELECT * FROM XXX
6A6E85CB-CCA3-E111-9E8E-005056C00008 1
6B6E85CB-CCA3-E111-9E8E-005056C00008 2
6C6E85CB-CCA3-E111-9E8E-005056C00008 3
**CCEA7AF2-CCA3-E111-9E8E-005056C00008 4** Gap here because we 'switched' to y
CDEA7AF2-CCA3-E111-9E8E-005056C00008 5
CEEA7AF2-CCA3-E111-9E8E-005056C00008 6
SELECT * FROM YYY
8F9438E1-CCA3-E111-9E8E-005056C00008 2012-05-22 07:13:35.503
909438E1-CCA3-E111-9E8E-005056C00008 2012-05-22 07:13:41.210
919438E1-CCA3-E111-9E8E-005056C00008 2012-05-22 07:13:41.220
Also, NewSequentialId()s aren't returned to the sequence in the case of a failed insert, e.g.
insert into XXX(x) values(1)
insert into XXX(x) values(2)
BEGIN TRAN
insert into XXX(x) values(3)
insert into XXX(x) values(4)
ROLLBACK TRAN
insert into XXX(x) values(5)
insert into XXX(x) values(6)
GO
686EFE5B-CDA3-E111-9E8E-005056C00008
696EFE5B-CDA3-E111-9E8E-005056C00008
6C6EFE5B-CDA3-E111-9E8E-005056C00008
6D6EFE5B-CDA3-E111-9E8E-005056C00008
i.e. a Gap of 2 Guids rolled back
and
insert into XXX(x) values(1)
insert into XXX(x) values(2)
insert into XXX(x) values(3)
GO
insert into XXX(x) values(99999999999999) -- overflow
GO
insert into XXX(x) values(4)
insert into XXX(x) values(5)
insert into XXX(x) values(6)
go
select * from xxx
AC613611-CFA3-E111-9E8E-005056C00008 1
AD613611-CFA3-E111-9E8E-005056C00008 2
AE613611-CFA3-E111-9E8E-005056C00008 3
**B0613611-CFA3-E111-9E8E-005056C00008 4** Gap of 1 - overflow failure
B1613611-CFA3-E111-9E8E-005056C00008 5
B2613611-CFA3-E111-9E8E-005056C00008 6
NEWSEQUENTIALGUID (as every guid generated in a way that warrant their sequence) includes a part of the Guid calculated via a time stamp. So if you run the inserts at different time you'll see some gaps.
But the important part is that the Guid are "ordered" in a way that do not cause page splits (if the Guid is used in a index) and this is what happens when using the new sequential guid.
I'm getting ready to release a stored procedure that gets info from other tables, does a pre-check, then inserts the good data into a (new) table. I'm not used to working with keys and new tables as much, and my insert into this new table I'm creating is having this error message having to do with the insert/key:
Msg 545, Level 16, State 1, Line 131
Explicit value must be specified for identity column in table 'T_1321_PNAnnotationCommitReport' either when IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR REPLICATION identity column.
BEGIN
...
BEGIN
IF NOT EXISTS (SELECT * FROM sys.tables where name = N'T_1321_PNAnnotationCommitReport')
BEGIN
CREATE TABLE T_1321_PNAnnotationCommitReport (
[id] [INT] IDENTITY(1,1) PRIMARY KEY NOT NULL, --key
[progressnote_id] [INT] NOT NULL,
[form_id] [INT] NOT NULL,
[question_id] [INT],
[question_value] [VARCHAR](max),
[associatedconcept_id] [INT],
[crte_date] [DATETIME] DEFAULT CURRENT_TIMESTAMP,
[create_date] [DATETIME] --SCHED_RPT_DATE
);
print 'test';
END
END --if not exists main table
SET IDENTITY_INSERT T_1321_PNAnnotationCommitReport ON;
...
INSERT INTO dbo.T_1321_PNAnnotationCommitReport--(progressnote_id,form_id,question_id,question_value,associatedconcept_id,crte_date, create_date) **I tried with and without this commented out part and it's the same.
SELECT progressnote_id,
a.form_id,
question_id,
questionvalue,
fq.concept_id,
getdate(),
a.create_date
FROM (
SELECT form_id,
progressnote_id,
R.Q.value('#id', 'varchar(max)') AS questionid,
R.Q.value('#value', 'varchar(max)') AS questionvalue,
create_date
FROM
#tableNotes t
OUTER APPLY t.form_questions.nodes('/RESULT/QUESTIONS/QUESTION') AS R(Q)
WHERE ISNUMERIC(R.Q.value('#id', 'varchar(max)')) <> 0
) a
INNER JOIN [CKOLTP_DEV]..FORM_QUESTION fq ON
fq.form_id = a.form_id AND
fq.question_id = a.questionid
--select * from T_1321_PNAnnotationCommitReport
SET IDENTITY_INSERT T_1321_PNAnnotationCommitReport OFF;
END
Any ideas?
I looked at some comparable inserts we do at work, insert into select and error message, and insert key auto-incremented, and I think I'm doing what they do. Does anyone else see my mistake? Thanks a lot.
To repeat my comment under the question:
The error is literally telling you the problem. You turn change the IDENTITY_INSERT property to ON for the table T_1321_PNAnnotationCommitReport and then omit the column id in your INSERT. If you have enabled IDENTITY_INSERT you need to supply a value to that IDENTITY, just like the error says.
We can easily replicate this problem with the following batches:
CREATE TABLE dbo.MyTable (ID int IDENTITY(1,1),
SomeValue varchar(20));
GO
SET IDENTITY_INSERT dbo.MyTable ON;
--fails
INSERT INTO dbo.MyTable (SomeValue)
VALUES('abc');
GO
If you want the IDENTITY value to be autogenerated, then leave IDENTITY_INSERT set to OFF and omit the column from the INSERT (like above):
SET IDENTITY_INSERT dbo.MyTable OFF; --Shouldn't be needed normally, but we manually changed it before
--works, as IDENTITY_INSERT IS OFF
INSERT INTO dbo.MyTable (SomeValue)
VALUES('abc');
If you do specifically want to define the value for the IDENTITY, then you need to both set IDENTITY_INSERT to ON and provide a value in the INSERT statement:
SET IDENTITY_INSERT dbo.MyTable ON;
--works
INSERT INTO dbo.MyTable (ID,SomeValue)
VALUES(10,'def');
GO
SELECT *
FROM dbo.MyTable;
IDENTITY_INSERT doesn't mean "Get the RDBMS to 'insert' the value" it means that you want to want to tell the RDBMS what value to INSERT. This is covered in the opening sentence of the documentation SET IDENTITY_INSERT (Transact-SQL):
Allows explicit values to be inserted into the identity column of a table.
(Emphasis mine)
I have a table which has several field including:
contact_id
phone
phone_id
contact_id and phone are primary keys and phone_id is an auto increment field. I want to use it to recognize a certain entry. So I want to know that is it possible to duplicate that non primary field when I'm entering data.
Unless there is no constraint, some unique index, you can duplicate values in that column, because 1) you can turn identity_insert on, 2) you can reseed increments.
Here is a proof:
CREATE TABLE #test(id INT IDENTITY(1, 1))
INSERT INTO #test DEFAULT VALUES
INSERT INTO #test DEFAULT VALUES
INSERT INTO #test DEFAULT VALUES
SET IDENTITY_INSERT #test ON
INSERT INTO #test(id) VALUES(1)
SET IDENTITY_INSERT #test OFF
INSERT INTO #test DEFAULT VALUES
INSERT INTO #test DEFAULT VALUES
DBCC CHECKIDENT ('#test', RESEED, 1);
INSERT INTO #test DEFAULT VALUES
INSERT INTO #test DEFAULT VALUES
SELECT * FROM #test
DROP TABLE #test
Output:
id
1
2
3
1
4
5
2
3
The short answer is Yes, it's possible.
SQL Server does not force a unique constraint on identity columns, meaning that the can have duplicated values, however, Sql server will not generate duplicate values itself in an identity column.
Identity columns in sql server are populated by the sql server itself when you insert a row to the table.
However, you can specify a value to them by using SET IDENTITY_INSERT before the insert statement.
There are a couple of things that you should be aware of:
Setting identity_insert on is per table. you can only set it for one table at the time.
Until you set the identity_insert back off, any insert statement to that table will have to specify a value for the identity column.
you can't use set identity insert on for more then one table on a single session. therefor after you've done inserting records to the table you must set the identity_insert back off on that table.
On a table, there's a delete trigger that performs some operations and then at the end, executes a select statement, so when you do something like...
delete from mytable where id=1
it returns a recordset.
Is there a way to save the results of that recordset into a temp table or something? I tried something like this:
declare #temptable table (returnvalue int);
insert into #temptable (returnvalue)
delete from mytable where id=1;
But apparently that syntax doesn't work.
Well,
I can not imagine a situation that you need to return the recordset of the line you will delete using a trigger returning a recordset. But I am not here to judge your requests.
Well, you can use the OUTPUT to show the row data that will be excluded and enter this data into a temporary table. Follow the example below.
However you should know that: SQL Server does not guarantee the order in Which rows are processed and returned by DML statements using the OUTPUT clause. It is up to the application to include an WHERE clause Appropriate que can guarantee the Desired semantics, or Understand que When multiple rows may qualify for the DML operation, there is guaranteed in order. The Following example uses the subquery and you assume uniqueness is a characteristic of the column in order to DatabaseLogID in Place the Desired ordering semantics. See the link.
Example:
CREATE TABLE Person
(
PersonID int,
LastName varchar(255),
FirstName varchar(255)
);
GO
--DECLARE #MyTablePerson TABLE
--(
-- PersonID int,
-- LastName varchar(255),
-- FirstName varchar(255)
--);
--GO
--CREATE TRIGGER TRG_DLT_Person
--ON Person
--INSTEAD OF DELETE
--AS
--BEGIN
-- Some code you want to do before delete
-- DELETE Person
-- FROM DELETED D
--END
--GO
insert into Person
(PersonID,
LastName,
FirstName)
values
(1,
'Kilmister',
'Lemmy');
GO
insert into Person
(PersonID,
LastName,
FirstName)
values
(2,
'Gilmour',
'David');
GO
insert into Person
(PersonID,
LastName,
FirstName)
values
(3,
'Rose',
'Axl');
GO
insert into Person
(PersonID,
LastName,
FirstName)
values
(4,
'Bullock',
'Sandra');
GO
--
select * from Person;
GO
delete from Person
--output deleted.* INTO #MyTablePerson
output deleted.*
WHERE PersonID = 4 OR PersonID = 2;
GO
select * from Person;
GO
select * from #MyTablePerson;
GO
I put the example I'm showing in a this environment, but in this environment believe that are not supported for temporary tables.
SQL Fiddle
Regardless of this being a bad practice due to it being difficult for anyone interacting with the table to know that it will happen and deal with it when it does, and regardless of it being possible to capture, one pretty solid reason to not return result sets from a trigger is that doing so will be disallowed as of one of the next versions of SQL Server, so you would have to re-code the functionality anyway. The MSDN page for the disallow results from triggers Server Configuration Option states:
Important
This feature will be removed in the next version of Microsoft SQL Server. Do not use this feature in new development work, and modify applications that currently use this feature as soon as possible. We recommend that you set this value to 1.
If you are merely returning something like SELECT IdField FROM deleted; from the trigger, then you should (well, really need to) use the OUTPUT clause instead.
That being said, doing the following will do what you want:
CREATE TABLE #TempResults
(
ReturnValue INT
);
INSERT INTO #TempResults (ReturnValue)
EXEC('DELETE FROM mytable WHERE id = 1;');
You can test with the following:
SET NOCOUNT ON;
IF (OBJECT_ID('dbo.DeleteTriggerWithResults') IS NOT NULL)
BEGIN
DROP TABLE dbo.DeleteTriggerWithResults;
END;
CREATE TABLE dbo.DeleteTriggerWithResults
(
Col1 INT NOT NULL IDENTITY(1, 1),
Col2 DATETIME DEFAULT (GETDATE())
);
GO
CREATE TRIGGER dbo.tr_DeleteTriggerWithResults_d
ON dbo.DeleteTriggerWithResults
AFTER DELETE
AS
BEGIN
SELECT Col1
FROM deleted;
END;
GO
INSERT INTO dbo.DeleteTriggerWithResults DEFAULT VALUES;
GO 30
SELECT * FROM dbo.DeleteTriggerWithResults;
And then run the test:
DECLARE #TempResults TABLE (Col1 INT);
INSERT INTO #TempResults (Col1)
EXEC('
DELETE TOP (10)
FROM dbo.DeleteTriggerWithResults;
');
SELECT * FROM #TempResults;
Returns:
Col1
-------
10
9
8
7
6
5
4
3
2
1
I have a Code (int) in my table, the ID is set to identity. How can I set a default value for my code to be filled by the same value az ID? I mean Identity.
You could use an after insert trigger:
create table TestTable (id int identity, col1 int)
go
create trigger TestTrigger on TestTable after insert
as begin
update TestTable
set col1 = id
where col1 is null
and id in (select id from inserted)
end
go
Test code:
insert TestTable default values
insert TestTable (col1) values (666)
insert TestTable default values
select * from TestTable
In general, I try to stay clear of triggers. In the long run using a stored procedure for insert is much more maintainable:
create procedure dbo.InsertTestRow(
#col1 int)
as
insert TestTable (col1) values (#col1)
if #col1 is null
begin
update TestTable
set col1 = id
where id = SCOPE_IDENTITY()
end
If it always has the same value - why don't you just drop that field. Otherwise it can be maintained with triggers (BEFORE INSERT one).
I'm looking for something in the
default value! If it is null it should
be filled with the same value as id
but if it is provided with some value,
it should keep that value
You could solve the issue by using coalesce in your queries instead.
create table T (ID int identity, ID2 int)
insert into T values (default)
insert into T values (null)
insert into T values (78)
select
ID,
coalesce(ID2, ID) as ID2
from T
Result
ID ID2
-- ---
1 1
2 2
3 78
Assuming your table's ID is an Identity column, you could consider using a constraint:
ALTER TABLE MyTable
ADD CONSTRAINT MyTableCodeDefault
DEFAULT IDENT_CURRENT('MyTable') FOR Code
This works for these use cases:
INSERT INTO MyTable DEFAULT VALUES
INSERT INTO MyTable ({columns NOT including 'Code'})
VALUES ({value list matching insert columns})
INSERT INTO MyTable (Code) VALUES (666)
INSERT INTO MyTable (Code) SELECT 8 UNION SELECT 13 UNION SELECT 21
But it does not work for bulk inserts:
INSERT INTO MyTable ({columns NOT including 'Code'})
SELECT {value list matching insert columns}
UNION
SELECT {value list matching insert columns}
UNION
SELECT {value list matching insert columns}
This restriction may seem onerous, but in my practical experience, it's rarely a problem. Most of the use cases I've encountered that need a default value involve user/UI 'convenience': don't force the user to pick a value if they don't want to.
OTOH, rarely do I encounter bulk insert situations where it's impractical to specify the value for the columns you're targeting.
You could use computed column, like this:
if object_id('TempTable') is not null drop table TempTable
create table TempTable (Id int identity(1,1), Code as Id)
insert into TempTable
default values
insert into TempTable
default values
insert into TempTable
default values
select * from TempTable
Of course if you have other columns, then you dont need default values:
if object_id('TempTable') is not null drop table TempTable
create table TempTable (Id int identity(1,1), Code as Id, SomethingElse int)
insert into TempTable (SomethingElse)
select 10 union all
select 11 union all
select 12
select * from TempTable
But, like zerkms said - why do you need two columns that are same?
If the field is an Identity field in SQL Server, the database engine will take care of its value. What we normally do is to read the record back (after inserting) to get to the generated Id.
EDIT: It sounds like you are trying to "override" the identity? If so, before you insert, run:
SET IDENTITY_INSERT [tableName] ON
You'll have to be careful not to insert a value that already exists. This can get tricky, though. So maybe consider removing the identity property altogether, and managing the default values yourself?