In SQL Server, a simple INSERT will do:
create table dbo.Foo ( ID int primary key identity, ParentID int not null foreign key references foo(ID) ) go insert dbo.Foo (parentId) values (1) select * from dbo.Foo
leads to
ID ParentID ----------- ----------- 1 1
If you try to insert a value that will be different from your identification seed, the insert will fail.
UPDATE:
The question is not too clear as to what the context is (i.e. it is code that should work in a live production system or just a DB configuration script), and from comments that seem difficult to code, the identifier may not be an option . Although the above code, as a rule, works fine in DB initialization scenarios, where the root hierarchy identifier can be known and constant, in the case of a forest (several roots with identifiers that are unknown in advance), the following should work as intended:
create table dbo.Foo ( ID int primary key identity, ParentID int not null foreign key references foo(ID) ) go insert dbo.Foo (parentId) values (IDENT_CURRENT('dbo.Foo'))
You can then query for the last name as usual ( SCOPE_IDENTITY , etc.). To solve @usr problems, the code is really transaction-safe, as shown in the following example:
insert dbo.Foo (parentId) values (IDENT_CURRENT('dbo.Foo')) insert dbo.Foo (parentId) values (IDENT_CURRENT('dbo.Foo')) insert dbo.Foo (parentId) values (IDENT_CURRENT('dbo.Foo')) select * from dbo.Foo select IDENT_CURRENT('dbo.Foo') begin transaction insert dbo.Foo (parentId) values (IDENT_CURRENT('dbo.Foo')) rollback select IDENT_CURRENT('dbo.Foo') insert dbo.Foo (parentId) values (IDENT_CURRENT('dbo.Foo')) select * from dbo.Foo
Result:
ID ParentID ----------- ----------- 1 1 2 2 3 3 currentIdentity --------------------------------------- 3 currentIdentity --------------------------------------- 4 ID ParentID ----------- ----------- 1 1 2 2 3 3 5 5
Serge Belov
source share