如何解决我开始学习T-SQL,并且在创建外键时遇到问题
我开始学习T-SQL,并尝试创建一个基本数据库并在表之间建立一些关系。这是我正在使用的代码:
CREATE DATABASE Colegio
ON PRIMARY
(NAME = ColegioPrimary,Filename = 'C:\Datos\ColegioPrimary.mdf',size = 500MB,filegrowth = 75%)
LOG ON
(NAME = ColegioLog,Filename = 'C:\Datos\ColegioLog.ldf',size = 100MB,filegrowth = 25%)
go
ALTER DATABASE Colegio
ADD FILEGROUP Produccion
go
ALTER DATABASE Colegio
ADD FILE (NAME = ColegioProduccion,Filename = 'C:\Datos\ColegioProduccion.ndf',size = 50MB,filegrowth = 25%) TO FILEGROUP Produccion
go
ALTER DATABASE Colegio
MODIFY filegroup[Produccion] DEFAULT
go
create table Estudiante
(
EstudianteID int identity(1,1) NOT NULL,Nombre nvarchar(20) NOT NULL,Apellido nvarchar(20) NOT NULL,Edad int NOT NULL,CONSTRAINT PK_EstudianteID PRIMARY KEY CLUSTERED(EstudianteID),CONSTRAINT CK_Edad CHECK(Edad >=3),ProfesorID int
)
GO
create table Profesor
(
ProfesorID int identity(1,1) not null,Nombre nvarchar(20) not null,apellido nvarchar(20) not null,profesion varchar(30) not null,edad int not null,CONSTRAINT PK_ProfesorID PRIMARY KEY CLUSTERED(ProfesorID),CONSTRAINT FK_Profesor_Estudiante FOREIGN KEY(EstudianteID) -- right here is the problem
references dbo.Estudiante(EstudianteID) on update cascade,constraint ck_edad check(edad >=20)
)
go
如上所述,尝试在“ Profesor”表中创建外键时引发错误。有人可以解释为什么会引发错误吗?
解决方法
创建外键约束时,需要引用当前表中存在的列以及与其链接到的表中的列。在上面指示的行中,您试图在仅在Estudiante表中存在的列'EstudianteID'上创建外键约束。您需要在“ Profesor”表中的整数列可以容纳外键值。
对于在“ Profesor”表上的创建,您需要以下内容:
CREATE TABLE Profesor
(
ProfesorID int identity(1,1) not null,EstudianteID int not null,--Adding this line here
Nombre nvarchar(20) not null,apellido nvarchar(20) not null,profesion varchar(30) not null,edad int not null,CONSTRAINT PK_ProfesorID PRIMARY KEY CLUSTERED(ProfesorID),CONSTRAINT FK_Profesor_Estudiante FOREIGN KEY(EstudianteID) references dbo.Estudiante(EstudianteID) on update cascade,constraint ck_edad check(edad >=20)
)
go
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。