USE jwglxt
go
if exists(select name from sys.tables where name='Teaching')
Drop table Teaching
go
create table Teaching
(
Tno char(8)not null,
Cno char(5)not null,
)
go
alter table Teacher
add constraint fk foreign key(Tno)references Teaching(Tno)
go
exec sp_helpconstraint Teacher
go
Alter table Course
add constraint fk foreign key(Cno)references Teaching(Cno)
go
EXEC sp_helpconstraint Course
------解决方案--------------------
你的外键得去跟主键关联,你逐渐都没设,肯定报错
------解决方案--------------------
- SQL code
CREATE TABLE [dbo].[Varrily] ( [ID] [bigint] NOT NULL , [Name] [char] (10) NULL , [Address] [char] (480) NULL , [Introduction] [ntext] NULL ) CREATE TABLE [dbo].[MyTable] ( [ID] [bigint] IDENTITY (1, 1) NOT NULL , [AuthorID] [bigint] NOT NULL , [Title] [char] (40) NULL , [Date_of_Created] [datetime] NULL ) 被引用的键必须唯一,可以设置为主键或者添加唯一约束。 alter table dbo.Varrily add constraint pk_id primary key (ID) alter table dbo.Varrily add constraint un_id unique (ID) alter table dbo.MyTable add constraint fk_AuthorID foreign key (AuthorID) references dbo.Varrily([ID])
------解决方案--------------------
参考:
示例
A. 使用 PRIMARY KEY 约束
下例显示在示例数据库 pubs 的 jobs 表中,job_id 列中具有聚集索引的 PRIMARY KEY 约束的列定义;此例由系统提供约束名。
job_id smallint
PRIMARY KEY CLUSTERED
下例显示如何为 PRIMARY KEY 约束提供名称。此约束用于 employee 表中的 emp_id 列。此列基于用户定义数据类型。
emp_id empid
CONSTRAINT PK_emp_id PRIMARY KEY NONCLUSTERED
B. 使用 FOREIGN KEY 约束
FOREIGN KEY 约束用于引用其它表。FOREIGN KEY 可以是单列键或多列键。下例显示 employee 表上引用 jobs 表的单列 FOREIGN KEY 约束。对于单列 FOREIGN KEY 约束,只需要 REFERENCES 子句。
job_id smallint NOT NULL
DEFAULT 1
REFERENCES jobs(job_id)
也可以显式使用 FOREIGN KEY 子句并复述列特性。注意在这两个表中列名不必相同。
FOREIGN KEY (job_id) REFERENCES jobs(job_id)
多列键约束作为表约束创建。在 pubs 数据库中,sales 表包含多列 PRIMARY KEY。下例显示如何从其它表中引用此键(可选择显式约束名)。
CONSTRAINT FK_sales_backorder FOREIGN KEY (stor_id, ord_num, title_id)
REFERENCES sales (stor_id, ord_num, title_id)
------解决方案--------------------
- SQL code
USE jwglxtgoif exists(select name from sys.tables where name='Teaching')Drop table Teaching gocreate table Teaching(Tno char(8)not null,Cno char(5)not null,)go--先给Teacher 和 Course表增加主键。假设主键列分别是:Tno,Cnoalter table Teacher add constraint pk_Teacher primary key(Tno)goalter table Course add constraint pk_Course primary key(Cno)go--再给Teaching 添加外键约束alter table Teachingadd constraint fk_Tno foreign key(Tno) references Teaching(Tno)goalter table Teachingadd constraint fk_Cno foreign key(Cno) references Teaching(Cno)go