使用复合PK和FK的链接表

时间:2016-02-11 13:35:57

标签: sql sql-server sql-server-2008-r2

我正在尝试创建一个链接表。链接的两个表格是PersonAddress。两个表的主键都为ID

CREATE TABLE LinkedTable
(
   EntryID INT NOT NULL IDENTITY,
   PersonID INT NOT NULL FOREIGN KEY REFERENCES Person(ID),
   AddressID INT NOT NULL FOREIGN KEY REFERENCES Address(ID),
   PRIMARY KEY(EntryID, PersonID, AddressID)
)

是否可以在表脚本中设置外键约束和复合主键?

1 个答案:

答案 0 :(得分:0)

CREATE TABLE [dbo].[LinkedTable] (
    [EntryID] [int] IDENTITY(1,1) NOT NULL
    , [PersonID] [bigint] NOT NULL
    , [AddressID] [int] NOT NULL
    , CONSTRAINT [PK_LinkedTable] PRIMARY KEY CLUSTERED (
        [EntryID] ASC
    ) WITH (
          PAD_INDEX = OFF
        , STATISTICS_NORECOMPUTE = OFF
        , IGNORE_DUP_KEY = OFF
        , ALLOW_ROW_LOCKS = ON
        , ALLOW_PAGE_LOCKS = ON
    ) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[LinkedTable]  WITH CHECK ADD FOREIGN KEY([PersonID])
REFERENCES [dbo].[Person] ([ID])
GO

ALTER TABLE [dbo].[LinkedTable]  WITH CHECK ADD FOREIGN KEY([AddressID])
REFERENCES [dbo].[Address] ([ID])
GO

CREATE UNIQUE NONCLUSTERED INDEX [IX_LinkedTable] ON [dbo].[LinkedTable] (
      [PersonID] ASC
    , [AddressID] ASC
) WITH (
      PAD_INDEX = OFF
    , STATISTICS_NORECOMPUTE = OFF
    , SORT_IN_TEMPDB = OFF
    , IGNORE_DUP_KEY = OFF
    , DROP_EXISTING = OFF
    , ONLINE = OFF
    , ALLOW_ROW_LOCKS = ON
    , ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
GO