sql server 2008中引用的表中没有主键或候选键

时间:2015-10-27 16:18:11

标签: sql-server

ClassCode表

CREATE TABLE [dbo].[ClassCode](
[SchoolCode] [nvarchar](10) NOT NULL,
[ClassCode] [nvarchar](4) NOT NULL,
[ClassName] [nvarchar](50) NOT NULL,
[ClassRange] [int] NOT NULL,
[ClassDuration] numeric(38,2) NOT NULL,
[UserID] [nvarchar](30) NULL,
[RecordDate] [smalldatetime] NULL,  
 CONSTRAINT [PK_ClassCode] PRIMARY KEY CLUSTERED 
(
    [SchoolCode] ASC,
    [ClassCode] ASC,
    [ClassRange]
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

考试声明表

CREATE TABLE [dbo].[ExamDeclaration](
[SchoolCode] [nvarchar](10) NOT NULL,
[ClassCode] [nvarchar](4) NOT NULL,
[ExamCode] [nvarchar](4) NOT NULL,
[RegistationFess] numeric(38,2) NOT NULL,
[RegistatinStartDate] [date] NOT NULL,
[RegistatinEndDate] [date] NOT NULL,
[ExamStartDate] [date] NOT NULL,
[UserID] [nvarchar](30) NULL,
[RecordDate] [smalldatetime] NULL
 CONSTRAINT [PK_ExamDeclaration] PRIMARY KEY CLUSTERED 
(
    [SchoolCode] ASC,
    [ClassCode] ASC,
    [ExamCode] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]


GO

ALTER TABLE [dbo].[ExamDeclaration]  WITH CHECK ADD  CONSTRAINT [FK_ExamDeclaration_ClassCode] FOREIGN KEY([ClassCode])
REFERENCES [dbo].[ClassCode] ([ClassCode])
GO

ALTER TABLE [dbo].[ExamDeclaration] CHECK CONSTRAINT [FK_ExamDeclaration_ClassCode]
GO

我正在尝试设置外键ClassCode

但是出现了这个错误

  

Msg 1776,Level 16,State 0,Line 2没有主要或候选人   引用表'dbo.ClassCode'中与之匹配的键   引用外键中的列列表   'FK_ExamDeclaration_ClassCode'。 Msg 1750,Level 16,State 0,Line 2   无法创建约束。查看以前的错误。消息4917,16级,   状态0,第2行约束'FK_ExamDeclaration_ClassCode'没有   存在。消息4916,级别16,状态0,行2无法启用或禁用   约束。查看以前的错误。

这两个表有什么问题?

谢谢..

1 个答案:

答案 0 :(得分:0)

您的外键必须与主键完全匹配! 如果你声明主键如 PK(X int,Y int,Z int),那么必须像这样声明FK: FK(一个int,b int,c int)引用MyTable(X,Y,Z)

在您的情况下,您的Pk是(SchoolCode,ClassCode,ClassRange)。这意味着您应该像这样声明FK:

$.ajax({ type: "post", dataType:"json", url: "json.php", success: function(a) { var test = a.data[0]['id']; } }); alert(test); //not working

修改你的表ExamDeclaration,添加'ClassRange'列。