正确的语法来声明外键

时间:2014-03-25 16:22:29

标签: sql-server

CREATE TABLE [dbo].[Book] (
   [Id]     INT           IDENTITY (1, 1) NOT NULL,
   [Auhor]  NVARCHAR (50) NOT NULL,
   [Name]   NVARCHAR (50) NOT NULL,
   [Price]  DECIMAL (18)  NOT NULL,
   [UserId] INT           NOT NULL,

   FOREIGN KEY ([UserId]) REFERENCES [dbo].[UserProfile] ([UserId])
);

CREATE TABLE [dbo].[UsedBook] (
   [Id]           INT          IDENTITY (1, 1) NOT NULL,
   [BookId]       INT          NOT NULL,
   [Email]        NCHAR (10)   NULL,
   [MobileNumber] VARCHAR (15) NULL,

   PRIMARY KEY CLUSTERED ([Id] ASC),
   FOREIGN KEY (BookID) REFERENCES [dbo].[Book]([Id])
);

您能否在UsedBook表中为我提供正确的外键命令语法?因为每次我试图运行它都会给我错误

  

SQL71516 ::引用的表' [dbo]。[Book]'不包含与外键中的引用列列表匹配的主键或候选键。如果引用的列是计算列,则应该保留它。

抱歉我的英语:)

1 个答案:

答案 0 :(得分:2)

将Book表中的[Id]转换为主键:

[Id] INT IDENTITY (1, 1) NOT NULL PRIMARY KEY