实体完整性
定义实体完整性
关系模型的实体完整性在CREATE TABLE中用PRIMARY KEY定义。对单属性构成的码有两种说明方法,一种是定义为列级约束条件,另一种是定义为表级约束条件。对多个属性构成的码只有一种说明方法,即定义为表级约束条件。
[例5.1]将Student表中的Sno定义为码
CREATE TABLE Student
(Sno CHAR(9) PRIMARY KEY, /*在列级定义主码*/
Sname CHAR(20) NOT NULL,
Ssex CHAR(2),
Sage SMALLINT,
Sdept CHAR(20)
);
或
CREATE TABLE Student
(Sno CHAR(9),
Sname CHAR(20) NOT NULL,
Ssex CHAR(2),
Sage SMALLINT,
Sdept CHAR(20),
PRIMARY KEY(Sno) /*在表级定义主码*/
);
[例5.2]将SC表中的Sno、Cno属性组定义为码
只能在表级定义主码:
CREATE TABLE SC
(Sno CHAR(9) NOT NULL,
Cno CHAR(4) NOT NULL,
Grade SMALLINT,
PRIMARY KEY(Sno,Cno)
);
参照完整性
定义参照完整性
关系模型的参照完整性在CREATE TABLE中用FOREIGN KEY短语定义哪些列为外码,用REFERENCES短语指明这些外码参照哪些表的主码。
[例5.3]定义SC表中的参照完整性
CREATE TABLE SC
(Sno CHAR(9) NOT NULL,
Cno CHAR(4) NOT NULL,
Grade SMALLINT,
PRIMARY KEY(Sno,Cno),
FOREIGN KEY Sno REFERENCES Student(Sno),
FOREIGN KEY Cno REFERENCES Student(Cno)
);
参照完整性检查和违约处理
[例5.4]显式说明参照完整性的违约处理示例
CREATE TABLE SC
(Sno CHAR(9) NOT NULL,
Cno CHAR(4) NOT NULL,
Grade SMALLINT,
PRIMARY KEY(Sno,Cno), /*在表级定义实体完整性,Sno、Cno都不能取空值*/
FOREIGN KEY Sno REFERENCES Student(Sno) /*在表级定义参照完整性*/
ON DELETE CASCADE /*当删除Student表中的元组时,级联删除SC表中相应的元组*/
ON UPDATE CASCADE, /*当更新Student表中的Sno时,级联更新SC表中的相应元组*/
FOREIGN KEY Cno REFERENCES Student(Cno)
ON DELETE NO ACTION /*当删除Course表中的元组造成与SC表不一致的时候,拒绝删除*/
ON UPDATE CASCADE /*当更新Course表中的Cno时,级联更新SC表中的相应元组*/
);
用户定义的完整性
属性上的约束条件
在CREATE TABLE中定义属性的同时,可以根据应用要求定义属性上的约束条件,即属性值限制,包括:
列值为非空(NOT NULL)
列值唯一(UNIQUE)
检查列值是否满足一个条件表达式(CHECK短语)
①不允许取空值
[例5.5]在定义SC表时,说明Sno、Cno、Grade属性不允许为空值
CREATE TABLE SC
(Sno CHAR(9) NOT NULL,
Cno CHAR(4) NOT NULL,
Grade SMALLINT NOT NULL,
PRIMARY KEY(Sno,Cno),
.
.
.
②列值唯一
[例5.6]建立部门表DEPT,要求部门名称Dname列值取值唯一,部门编号
Deptno列为主码
CREATE TABLE DEPT
(Deptno NUMERIC(2) PRIMARY KEY,
Dname CHAR(9) UNIQUE,
Location CHAR(10)
);
③用CHECK短语指定列值应该满足的条件
[例5.7]Student表中的Ssex只能取‘男’或‘女’
CREATE TABLE Student
(Sno CHAR(9) PRIMARY KEY,
Sname CHAR(20) NOT NULL,
Ssex CHAR(2) CHECK (Ssex IN ('男','女')),
Sage SMALLINT,
Sdept CHAR(20)
);
[例5.8]SC表的Grade值应在0到100之间
CREATE TABLE SC
(Sno CHAR(9) NOT NULL,
Cno CHAR(4) NOT NULL,
Grade SMALLINT CHECK (Grade >= 0 AND Grade <= 100),
PRIMARY KEY(Sno,Cno),
FOREIGN KEY Sno REFERENCES Student(Sno),
FOREIGN KEY Cno REFERENCES Student(Cno)
);
元组上的约束条件
与属性上约束条件的定义类似,在CREATE TABLE语句中可以用CHECK语句定义元组上的约束条件,即元组级的限制,同属性值限制相比,元组级的限制可以设置不同属性之间的取值的相互约束条件。
[例5.9]当学生的性别是男时,其名字不能用‘Ms.’打头
CREATE TABLE Student
(Sno CHAR(9) PRIMARY KEY,
Sname CHAR(8) NOT NULL,
Ssex CHAR(2),
Sage SMALLINT,
Sdept CHAR(20),
CHECK (Ssex='女' OR Sname NOT LIKE 'Ms.%')
);
完整性约束命名子句
完整性约束命名子句
CONSTRAINT <完整性约束条件名> <完整性约束条件>
完整性约束条件包括NOT NULL、UNIQUE、PRIMARY KEY、FOREIGN KEY、CHECK短语
[例5.10]建立学生登记表Student,要求学号在90000~99999之间,姓名不能取空值,年龄小于30,性别只能是‘男’或‘女’
CREATE TABLE Student
(Sno NUMERIC(6)
CONSTRAINT C1 CHECK(Sno BETWEEN 90000 AND 99999),
Sname CHAR(20)
CONSTRAINT C2 NOT NULL,
Sage NUMERIC(3)
CONSTRAINT C3 CHECK(Sage<30),
Ssex CHAR(2)
CONSTRAINT C4 CHECK(Ssex IN('男','女')),
CONSTRAINT StudentKey PRIMARY KEY(Sno)
);
[例5.11]建立教师表TEACHER,要求每个教师的应发工资不低于3000元。应发工资列Sal与扣除项Deduct之和
CREATE TABLE TEACHER
(Eno NUMERIC(4) PRIMARY KEY,
Ename CHAR(10),
Job CHAR(8),
Sal NUMERIC(7,2),
Deduct NUMERIC(7,2),
Deptno NUMERIC(2),
CONSTRAINT TEACHERKey FOREIGN KEY(Deptno)
REFERENCES DEPT(Deptno),
CONSTRAINT C1 CHECK(Sal+Deduct>=3000)
);
修改表中的完整性限制
[例5.12]去掉例5.10Student表中对性别的限制
ALTER TABLE Student
DROP CONSTRAINT C4;
[例5.13]修改表Student中的约束条件,要求学号在900000-999999之间,年龄由小于30改为小于40
ALTER TABLE Student
DROP CONSTRAINT C1
ALTER TABLE Student
ADD CONSTRAINT C1 CHECK(Sno BETWEEN 900000 AND 999999)
ALTER TABLE Student
DROP CONSTRAINT C3
ALTER TABLE Student
ADD CONSTRAINT C3 CHECK(Sage<40);
触发器
触发器又叫做事件-条件-动作规则。当特定的系统事件(如对一个表的增、删、改操作,事物的结束等)发生时,对规则的条件进行检查,如果条件成立则执行规则中的动作,否则不执行该动作。规则中的动作体可以很复杂,可以涉及其他表和其他数据库对象,通常是一段SQL存储过程。
建立触发器:
CREATE TRIGGER <触发器名>
{BEFORE|AFTER} <触发事件> ON <表名>
REFERENCING NEW|OLD ROW AS <变量>
FOR EACH {ROW|STATEMENT}
[WHEN <触发条件>]<触发动作体>
[例5.21]当对表SC的Grade属性进行修改时,若分数增加了10%,则将此操作记录到另一个表SC_U(Sno,Cno,Oldgrade,Newgrade)中,其中Oldgrade是修改前的分数,Newgrade是修改后的分数
先创建S_C表:
CREATE TABLE SC_U
(Sno CHAR(10) NOT NULL,
Cno CHAR(5) NOT NULL,
Oldgrade SMALLINT
CONSTRAINT C6 CHECK(Oldgrade BETWEEN 0 AND 100),
Newgrade SMALLINT
CONSTRAINT C7 CHECK(Newgrade BETWEEN 0 AND 100),
CONSTRAINT SCKEY PRIMARY KEY(Sno,Cno)
);
定义触发器:
CREATE TRIGGER SC_T
AFTER UPDATE OF Grade ON SC
REFERENCING
OLDROW AS OldTuple,
NEWROW AS NewTuple
FOR EACH ROW
WHEN(NewTuple.Grade>=1.1*OldTuple.Grade)
INSERT INTO SC_U(Sno,Cno,OldGrade,NewGrade)
VALUES(OldTuple.Sno,OldTuple.Cno,OldTuple.Grade,NewTuple.Grade);
T-SQL:
CREATE TRIGGER SC_T
ON SC
FOR UPDATE
AS
declare @OLD SMALLINT
declare @NEW SMALLINT
declare @SNO CHAR(9)
declare @CNO CHAR(4)
IF(UPDATE(Grade))
BEGIN
select @OLD =Grade FROM DELETED
select @NEW =Grade FROM INSERTED
select @SNO =Sno FROM DELETED
select @CNO =Cno FROM DELETED
IF(@NEW>=1.1*@OLD)
INSERT INTO SC_U(Sno,Cno,Oldgrade,Newgrade)
VALUES (@SNO,@CNO,@OLD,@NEW)
END
[例5.22]将每次对表Student的插入操作所增加的学生个数记录到表StudentInsertLog中
先建立StudentInsertLog表
CREATE TABLE StudentInsertLog
(Numbers INT);
建立StudentInsertLogUser表存储用户名和操作时间
CREATE TABLE StudentInsertLogUser
( UserName nchar(10),
DateAndTime datetime
);
创建触发器Student_Count,记录学生人数
CREATE TRIGGER Student_Count
AFTER INSERT ON Student
REFERENCING
NEW TABLE AS DELTA
FOR EACH STATEMENT
INSERT INTO StudentInsertLog
SELECT COUNT(*) FROM DELTA
T-SQL:
CREATE TRIGGER Student_Count
ON Student
AFTER
INSERT
AS
INSERT INTO StudentInsertLog(Numbers)
SELECT COUNT(*) FROM Student
创建触发器,记录用户名和操作时间
CREATE TRIGGER Student_Time
ON Student
AFTER
INSERT
AS
declare @UserName nchar(10)
declare @DateTime datetime
select @UserName = system_user
select @DateTime = CONVERT(datetime,GETDATE(),120)
INSERT INTO StudentInsertLogUser(UserName,DateAndTime)
VALUES (@UserName,@DateTime)
测试:
INSERT
INTO Student
VALUES ('201215998','林海','男',19,'MA');
SELECT * FROM Student;
SELECT * FROM StudentInsertLog;
SELECT * FROM StudentInsertLogUser;
[例5.23定义一个BEFORE行级触发器,为教师表Teacher定义完整性规则,教授的工资不低于4000元,如果低于4000元,自动改为4000元
先建立Teacher表:
CREATE TABLE Teacher(
Tno CHAR(9),
Tname CHAR(9),
Job CHAR(9),
Sal SMALLINT
)
建立触发器:
CREATE TRIGGER Insert_Or_Update_Sal
BEFORE INSERT OR UPDATE ON Teacher
REFERENCING NEW row AS newTuple
FOR EACH ROW
BEGIN
IF(newtuple.Job='教授')AND(newtuple.Sal<4000)
THEN newtuple.Sal=4000
END IF
END
T-SQL:
CREATE TRIGGER Insert_Or_Update_Sal
ON Teacher
FOR UPDATE,INSERT
AS
IF UPDATE(Sal)
BEGIN
declare @TNO CHAR(9)
declare @TNAME CHAR(9)
declare @JOB CHAR(9)
declare @SAL SMALLINT
select @SAL = Sal FROM INSERTED
select @TNO =Tno FROM Teacher
select @TNAME =Tname FROM Teacher
select @JOB =Job FROM Teacher
IF(@SAL<4000 AND @JOB='教授')
UPDATE Teacher
SET SAL=4000
WHERE Sal<4000 AND Job='教授'
END
插入数据测试:
INSERT INTO Teacher VALUES('1','张明','教授','2000');
INSERT INTO Teacher VALUES('2','王晨','教师','2000');
INSERT INTO Teacher VALUES('3','李磊','教授','5000');
存储过程
[例8.8]利用存储过程来实现下面的应用:从账户1转指定数额的款项到账户2中
建表Account并插入两个账户
CREATE TABLE Account
(
accountnum CHAR(3), -- 账户编号
total FLOAT -- 账户余额
);
INSERT INTO Account VALUES(101,50);
INSERT INTO Account VALUES(102,100);
SELECT * FROM Account;
IF (exists (select * from sys.objects where name = 'Proc_TRANSFER'))
DROP PROCEDURE Proc_TRANSFER --有该存储过程就先删除
GO
CREATE PROCEDURE Proc_TRANSFER
@inAccount INT,@outAccount INT,@amount FLOAT
/*定义存储过程TRANSFER,参数为转入账户、转出账户、转账额度*/
AS
BEGIN TRANSACTION TRANS
DECLARE /*定义变量*/
@totalDepositOut Float,
@totalDepositIn Float,
@inAccountnum INT;
/*检查转出账户的余额 */
SELECT @totalDepositOut = total FROM Account WHERE accountnum = @outAccount;
/*如果转出账户不存在或账户中没有存款*/
IF @totalDepositOut IS NULL
BEGIN
PRINT '转出账户不存在或账户中没有存款'
ROLLBACK TRANSACTION TRANS; /*回滚事务*/
RETURN;
END;
/*如果账户存款不足*/
IF @totalDepositOut < @amount
BEGIN
PRINT '账户存款不足'
ROLLBACK TRANSACTION TRANS; /*回滚事务*/
RETURN;
END
/*检查转入账户的状态 */
SELECT @inAccountnum = accountnum FROM Account WHERE accountnum = @inAccount;
/*如果转入账户不存在*/
IF @inAccountnum IS NULL
BEGIN
PRINT '转入账户不存在'
ROLLBACK TRANSACTION TRANS;/*回滚事务*/
RETURN;
END;
/*如果条件都没有异常,开始转账。*/
BEGIN
UPDATE Account SET total = total - @amount WHERE accountnum = @outAccount; /* 修改转出账户余额,减去转出额 */
UPDATE Account SET total = total + @amount WHERE accountnum = @inAccount; /* 修改转入账户余额,增加转入额 */
PRINT '转账完成,请取走银行卡'
COMMIT TRANSACTION TRANS; /* 提交转账事务 */
RETURN;
END
测试:
EXEC Proc_TRANSFER
@inAccount = 101, --转入账户
@outAccount = 102, --转出账户
@amount = 50 --转出金额
SELECT * FROM Account
EXEC Proc_TRANSFER
@inAccount = 101, --转入账户
@outAccount = 102, --转出账户
@amount = 100 --转出金额
EXEC Proc_TRANSFER
@inAccount = 103, --转入账户
@outAccount = 102, --转出账户
@amount = 50 --转出金额
[例8.9]从账户68转10000元到28账户中
建立账户
INSERT INTO Account VALUES('68','20000');
INSERT INTO Account VALUES('28','1500');
转入
EXEC Proc_TRANSFER
@inAccount = 01003813828,
@outAccount = 01003815868,
@amount = 10000