且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Visual Studio 2012中通过添加外键引用两个表?

更新时间:2023-01-29 09:57:52

由于Contact表中的 ContactOwnerId 应该是 FOREIGN KEY 指定在 CONSTRAINT 而不是UserId。

Since ContactOwnerId in the Contact table should be the FOREIGN KEY, you need to specify that in your CONSTRAINT instead of UserId.

我认为这是你想要做的: / p>

I think this is what you're trying to do:

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])
);

问题出在最后一行。您需要首先从联系人表中引用该列,然后指向您的UserProfile表。你有倒退。

The problem was with the last line. You need to reference the column from the Contacts table first, and then point to your UserProfile table. You had that backwards.

这是一个SQL小提琴

以下是一些创建外部关键字约束的文档/示例

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