2014-04-15 67 views
2

我有2個表,像這樣一些領域:如何插入autoNumbersCode到另一個表

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

CompanyTable.contactCode是分配給ContactTable.contactCode

,也CompanyTable.companyCodeCompanyTable.contactCode是autoNumbers foregin關鍵。

當我插入在contactTable新紀錄,我想插入它的contactCode到CompanyTable.contactCode這樣的:

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

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

如何獲得插入查詢後最新的標識值?

謝謝

回答

2

使用@@IDENTITY檢索最新生成的標識值。

在插入查詢後執行它。

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

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

您可以添加一個觸發器來添加contactCode。它應該是這樣的:

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 
相關問題