代码之家  ›  专栏  ›  技术社区  ›  Janilson

如何在多表继承中使用IDENTITY PK列(表/类型继承)

  •  1
  • Janilson  · 技术社区  · 8 年前

    我想要一个带有父表和几个派生表的数据库架构,例如:

    CREATE TABLE Base(
        [Id] [int] Identity(1,1) primary key clustered,
        [field1] [varchar](80) NOT NULL,
        [field2] [datetime] NOT NULL,
        --...
    )
    
    CREATE TABLE DerivedA(
        [Id] [int] primary key clustered,
        [field1] [varchar](10) NOT NULL,
        --...
    )
    
    CREATE TABLE DerivedB(
        [Id] [int] primary key clustered,
        [field1] [varchar](50) NOT NULL,
        [field1] [varchar](50) NOT NULL,
        --...
    )
    
    CREATE TABLE DerivedC(
        [Id] [int] primary key clustered,
        [field1] [varbinary](100) NOT NULL,
        --...
    )
    
    -- and so on...
    

    当然,我希望我的派生表在引用基表上的ID的ID上有一个外键约束,但是当基表pk是标识字段时,我不确定如何这样做,因为插入行时会生成ID。

    2 回复  |  直到 8 年前
        1
  •  2
  •   RBarryYoung    8 年前

    正确的方法很大程度上取决于如何批量输入数据以及如何将数据添加到相关表中的具体细节,但通常,某种形式的output子句可以完成如下所示的工作:

    -- base table to store the data
    CREATE TABLE Base(
        ID      int Identity(1,1) primary key clustered,
        ExtGuid UNIQUEIDENTIFIER,
        Other1  varchar(99)
    );
    go
    
    
    -- temp table to represent the input data/stream
    Create Table #tmp(ExtGuid UNIQUEIDENTIFIER, OtherData varchar(99));
    GO
    
    -- table variable to hold the output
    Declare @CreatedIds table (ID int, ExtGuid UNIQUEIDENTIFIER)
    
    -- insert the input data/stream and capture the IDs created
    INSERT INTO Base(ExtGuid, Other1)
    OUTPUT inserted.ID, inserted.ExtGuid INTO @CreatedIds
    SELECT t.ExtGuid, t.OtherData 
    FROM #tmp t
    ;
    
    -- one way to return the results
    Select * from @CreatedIds
    
        2
  •  1
  •   The Impaler    8 年前

    插入父行时,SQL Server将为您提供刚刚插入的标识pk标识的值,方法是:

    select scope_identity()
    

    可以使用此值插入相关行。