About the cheked answer:
You cannot do this - because the actual value that will be used for the IDENTITY column is really only fixed and set when the INSERT is complete.
marc_s I suppose you are actually wrong. Yes, he can! )))
Solution: IDENT_CURRENT() :
CREATE TABLE TemporaryTable( Id int PRIMARY KEY IDENTITY(1,1) NOT NULL, FkId int NOT NULL ) ALTER TABLE TemporaryTable ADD CONSTRAINT [Fk_const] FOREIGN KEY (FkId) REFERENCES [TemporaryTable] ([Id]) INSERT INTO TemporaryTable (FkId) VALUES (IDENT_CURRENT('[TemporaryTable]')) INSERT INTO TemporaryTable (FkId) VALUES (IDENT_CURRENT('[TemporaryTable]')) INSERT INTO TemporaryTable (FkId) VALUES (IDENT_CURRENT('[TemporaryTable]')) INSERT INTO TemporaryTable (FkId) VALUES (IDENT_CURRENT('[TemporaryTable]')) UPDATE TemporaryTable SET [FkId] = 3 WHERE Id = 2 SELECT * FROM TemporaryTable DROP TABLE TemporaryTable
Moreover, you can even use IDENT_CURRENT() as DEFAULT CONSTRAINT , and it works instead of SCOPE_IDENTITY() , for example. Try the following:
CREATE TABLE TemporaryTable( Id int PRIMARY KEY IDENTITY(1,1) NOT NULL, FkId int NOT NULL DEFAULT IDENT_CURRENT('[TemporaryTable]') ) ALTER TABLE TemporaryTable ADD CONSTRAINT [Fk_const] FOREIGN KEY (FkId) REFERENCES [TemporaryTable] ([Id]) INSERT INTO TemporaryTable (FkId) VALUES (DEFAULT) INSERT INTO TemporaryTable (FkId) VALUES (DEFAULT) INSERT INTO TemporaryTable (FkId) VALUES (DEFAULT) INSERT INTO TemporaryTable (FkId) VALUES (DEFAULT) UPDATE TemporaryTable SET [FkId] = 3 WHERE Id = 2 SELECT * FROM TemporaryTable DROP TABLE TemporaryTable
Jonik source share