Question

I have 2 tables with some fields like this:

CompanyTable (companyCode, name, contactCode)
ContactTable (contactCode, address, phone)

CompanyTable.contactCode is foregin key that assign to ContactTable.contactCode

and also CompanyTable.companyCode and CompanyTable.contactCode are autoNumbers.

when I insert new record in contactTable, I want to insert it's contactCode into CompanyTable.contactCode like this:

insert into contactTable ( address, phone) values ('x', 'x')

update companyTable set company.contactCode = ---------

How to get latest identity value after insert query?

Thanks

Was it helpful?

Solution

Use @@IDENTITY to retrieve latest generated Identity value.

execute it after your insert query.

insert into contactTable ( address, phone) values ('x', 'x')

DECLARE @contactCode INT;
SELECT @contactCode = @@IDENTITY;
update companyTable set company.contactCode = @contactCode Where companyCode=1

OTHER TIPS

You can add a trigger to add the contactCode. It would look like this:

CREATE TRIGGER trgUpdateCompanyTable
   ON  dbo.ContactTable
   AFTER INSERT
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @id INTEGER

    SET @id = (SELECT IDENT_CURRENT('ContactTable'))

    INSERT INTO CompanyTable (contactCode)
    VALUES (@id)

END
GO
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top