2016-02-11 52 views
-1

我想創建一個鏈接表。兩個表格鏈接的是PersonAddress。兩個表都有一個主鍵ID使用複合PK和FK的鏈接表

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

你試過了嗎?發生了什麼? – jarlh

+0

@jarlh說實話,我沒有我的電腦,它有SQL服務器,所以我不能夠嘗試在這一刻 – terbubbs

+1

對於一個複合鍵,我相信你需要添加它作爲自己的表中的約束線創建(而不是內聯每列)。國際海事組織,無論如何,這是首選方法。我希望你也能爲你的鑰匙命名。 –

回答

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