2016-06-12 46 views
0

我正在爲學校進行任務,而且我是一名SQL的確定新手。我試圖在電影作爲我的主要關鍵字之間建立數據集(即IMDb評級,流派,製片人等)之間的外鍵關係。當我嘗試設置表格和列規範之間的關係時,出現以下錯誤。SQL Server外鍵問題單元3分配

截圖:

USE [Movies] 
GO 
/****** Object: Table [dbo].[Directors] Script Date: 6/12/2016 2:42:27 PM ******/ 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
CREATE TABLE [dbo].[Directors]([DirectorID] [nchar](10) NOT NULL, [FirstName] [nvarchar](max) NULL, [LastName] [nvarchar](max) NULL, CONSTRAINT [PK_Directors] PRIMARY KEY CLUSTERED([DirectorID] ASC) 
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] 
TEXTIMAGE_ON [PRIMARY] 
GO 
ALTER TABLE [dbo].[Directors] WITH CHECK 
    ADD CONSTRAINT [FK_Directors_Directors] FOREIGN KEY([DirectorID]) REFERENCES [dbo].[Directors] ([DirectorID]) 
GO 
ALTER TABLE [dbo].[Directors] CHECK CONSTRAINT [FK_Directors_Directors] 
GO 
USE [Movies] 
GO 
/****** Object: Table [dbo].[Movie] Script Date: 6/12/2016 2:45:59 PM ******/ 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
SET ANSI_PADDING ON 
GO 
CREATE TABLE [dbo].[Movie]([MoviesID] [int] IDENTITY(1,1) NOT NULL, [Movies] [varchar](max) NOT NULL, 
    CONSTRAINT [PK_Movie] PRIMARY KEY CLUSTERED ([MoviesID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 
GO 
SET ANSI_PADDING OFF 
GO 
+2

歡迎來到Stack Overflow,Seth。請回顧[如何提出一個好問題?](http://stackoverflow.com/help/how-to-ask)和[如何創建一個最小,完整和可驗證的示例](http:// stackoverflow。 com/help/mcve),然後查看是否可以向我們提供更多信息。 –

+0

嗨達爾文,該任務是創建一個數據庫,其主鍵是「電影」與子鍵,如流派,生產者,IMDb_Rating等,我必須鏈接到主關鍵電影的子鍵(外鍵)。它錯誤我們與上面的截圖。這是來自任務的一個提示。我們將創造DirectorID,GenreID,ProducerID和LeadStarID外鍵的表導演,流派,生產者和LeadStar在電影表中的ID鏈接到ID。 – Seth

+0

我使用的是Microsoft SQL Server Management Studio中2012 – Seth

回答

0

嘗試與相同尺寸/類型的第一添加字段,然後才創建關係:

enter image description here

爲添加在註釋中的附加信息

ALTER TABLE [dbo].[Movie] ADD [DirectorID] [nchar](10); 
GO 
ALTER TABLE [dbo].[Movie] ADD CONSTRAINT [FK_Movie_Directors] 
FOREIGN KEY([DirectorID]) REFERENCES [dbo].[Directors] ([DirectorID]); 
GO