4

我在将外键添加到表列时遇到问题。我的桌子是这样的。我需要ContactOwnerIdContactUserId中引用到UserProfile表中

CREATE TABLE [dbo].[Contacts] (
    [ContactId] INT            IDENTITY (1, 1) NOT NULL,
    [ContactOwnerId]    INT            NOT NULL,
    [FirstName] NVARCHAR (MAX) NOT NULL,
    [LastName]  NVARCHAR (MAX) NOT NULL,
    [Address]   NVARCHAR (MAX) NOT NULL,
    [City]      NVARCHAR (MAX) NOT NULL,
    [Phone]     NVARCHAR (MAX) NOT NULL,
    [Email]     NVARCHAR (MAX) NOT NULL,
    CONSTRAINT [PK_dbo.Contacts] PRIMARY KEY CLUSTERED ([ContactId] ASC), 
    CONSTRAINT [FK_Contacts_UserProfile] FOREIGN KEY ([UserId]) REFERENCES [Contacts]([ContactOwnerId])
);

CREATE TABLE [dbo].[UserProfile] (
    [UserId]   INT           IDENTITY (1, 1) NOT NULL,
    [UserName] NVARCHAR (56) NOT NULL,
    PRIMARY KEY CLUSTERED ([UserId] ASC),
    UNIQUE NONCLUSTERED ([UserName] ASC)
);

我添加了一个外键,但似乎不对,因为 UserId 突出显示,给出错误:

SQL71501 :: Foreign Key: [dbo].[FK_Contacts_UserProfile] has an unresolved reference to Column [dbo].[Contacts].[UserId].
SQL71516 :: The referenced table '[dbo].[Contacts]' contains no primary or candidate keys that match the referencing column list in the foreign key. If the referenced column is a computed column, it should be persisted.

如何正确引用这两个表?提前致谢。

编辑 我确实像sgeddes说的那样。但是当我尝试创建联系人时出现错误。INSERT 语句与 FOREIGN KEY 约束“FK_Contacts_UserProfile”冲突。冲突发生在数据库“ContactAppContext”、表“dbo.UserProfile”、列“UserId”中。该语句已终止。

如果我删除外键,我不会收到错误。

我想要实现的是,当用户创建联系人时,他的 Id(UserId) 可以与 ContactOwnerId 关联,以便联系人可以与一个特定用户相关联。

4

1 回答 1

3

由于ContactOwnerId在 Contact 表中应该是FOREIGN KEY,因此您需要在您的CONSTRAINT而不是 UserId 中指定它。

我认为这就是你想要做的:

CREATE TABLE [dbo].[UserProfile] (
    [UserId]   INT           IDENTITY (1, 1) NOT NULL,
    [UserName] NVARCHAR (56) NOT NULL,
    PRIMARY KEY CLUSTERED ([UserId] ASC),
    UNIQUE NONCLUSTERED ([UserName] ASC)
);

CREATE TABLE [dbo].[Contacts] (
    [ContactId] INT            IDENTITY (1, 1) NOT NULL,
    [ContactOwnerId]    INT            NOT NULL,
    [FirstName] NVARCHAR (MAX) NOT NULL,
    [LastName]  NVARCHAR (MAX) NOT NULL,
    [Address]   NVARCHAR (MAX) NOT NULL,
    [City]      NVARCHAR (MAX) NOT NULL,
    [Phone]     NVARCHAR (MAX) NOT NULL,
    [Email]     NVARCHAR (MAX) NOT NULL,
    CONSTRAINT [PK_dbo.Contacts] PRIMARY KEY CLUSTERED ([ContactId] ASC), 
    CONSTRAINT [FK_Contacts_UserProfile] FOREIGN KEY ([ContactOwnerId]) REFERENCES [UserProfile]([UserId])
);

问题出在最后一行。您需要首先引用 Contacts 表中的列,然后指向您的 UserProfile 表。你倒过来了。

这是一个 SQL Fiddle

这是一些用于创建的文档/示例FOREIGN KEY CONSTRAINTS

http://msdn.microsoft.com/en-us/library/aa258255(v=sql.80).aspx

于 2013-05-25T15:32:25.647 回答