引用表中的列无效

时间:2013-05-04 16:43:26

标签: sql-server-2008-r2

我在新数据库中设置几个表。我有一个Users表,一个Companies表,一个UserCompanies表(因此用户可以为许多不同的公司工作)和一个UserPay表。

CREATE TABLE tblUsers
(
[UserTableID] INT IDENTITY NOT NULL PRIMARY KEY,    
[UserEmail] VARCHAR(50) NOT NULL,
[UserFirstName] VARCHAR(20) NOT NULL,
[UserLastName] VARCHAR(20) NOT NULL,
[UserAddress1] VARCHAR(45) NULL,
[UserAddress2] VARCHAR(45) SPARSE NULL,
[UserCity] VARCHAR(45) NULL,
[UserState] VARCHAR(2) NULL,
[UserZipCode] VARCHAR(10) NULL,
[UserPhone] VARCHAR(13) NULL,
)

CREATE TABLE tblCompanies
(
[CompanyID] INT IDENTITY NOT NULL PRIMARY KEY,
[CompanyName] VARCHAR(45) NOT NULL,
[CompanyAddress1] VARCHAR(45) NULL,
[CompanyAddress2] VARCHAR(45) SPARSE NULL,
[CompanyCity] VARCHAR(45) NULL,
[CompanyState] VARCHAR(2) NULL,
[CompanyPhone] VARCHAR(13) NULL,
[CompanyPhoneExtension] VARCHAR(8) NULL,
[CompanyContactFirstName] VARCHAR(20) NOT NULL,
[CompanyContactLastName] VARCHAR(20) NOT NULL
)

CREATE TABLE tblUserCompanies
(
[UserTableID] INT NOT NULL,
[CompanyID] INT NOT NULL,
PRIMARY KEY (UserTableID, CompanyID),
FOREIGN KEY (UserTableID) REFERENCES tblUsers(UserTableID),
FOREIGN KEY (CompanyID) REFERENCES tblCompanies(CompanyID)  
)

CREATE TABLE tblUserPay
(
[UserPayID] INT IDENTITY NOT NULL PRIMARY KEY,
[UserID] INT NOT NULL REFERENCES tblUserCompanies(UserTableID),
[UserCompany] INT NOT NULL REFERENCES tblUserCompanies(CompanyID),
[NetPay] MONEY NOT NULL,
[PayDate] DATE NOT NULL
)

问题是我收到一条错误,指出...“引用表tblUserCompanies中没有与tblUserPay中的引用列列表匹配的主键或候选键。

我不明白为什么我会收到错误。相同的数据类型,外键,主密钥建立。我唯一能想到的是它抛出一个错误,因为我有一个外键链接到另一个外键。如果可以的话请帮忙!感谢

2 个答案:

答案 0 :(得分:1)

链接到复合键时,您需要有一个包含两列的外键引用,如:

CREATE TABLE tblUserPay
(
[DriverPayID] INT IDENTITY NOT NULL PRIMARY KEY,
[UserID] INT NOT NULL,
[UserCompany] INT NOT NULL,
[NetPay] MONEY NOT NULL,
[PayDate] DATE NOT NULL,
FOREIGN KEY (UserID, UserCompany) REFERENCES tblUserCompanies(UserTableID, CompanyID)
)

答案 1 :(得分:0)

关注此示例

CREATE TABLE dbo.Table1(
    Table1Col1 int NOT NULL
    ,Table1Col2 int NOT NULL
    ,CONSTRAINT PK_Table1 PRIMARY KEY CLUSTERED(
        Table1Col1
        ,Table1Col2)    
);

CREATE TABLE dbo.Table2(
    Table2Col1 int NOT NULL
        CONSTRAINT PK_Table2 PRIMARY KEY CLUSTERED 
    ,Table1Col1 int NOT NULL
    ,Table1Col2 int NOT NULL
    ,CONSTRAINT FK_Table2_Table1 FOREIGN KEY(
        Table1Col1
        ,Table1Col2)
        REFERENCES dbo.Table1(
        Table1Col1
        ,Table1Col2
    )
);