【发布时间】:2013-05-25 15:21:16
【问题描述】:
我在向表列添加外键时遇到问题。
我的桌子是这样的。我需要将ContactOwnerId 从Contact 表引用到UserId 在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 关联,以便联系人可以与一个特定的用户相关。
【问题讨论】:
标签: sql database tsql foreign-keys