1.使用T-SQL创建表SC2,包含sno、cno、grade字段,并在sno和cno两列上建立表级主键约束。
CREATE TABLE SC2 (
sno CHAR(4) NOT NULL,
cno CHAR(4) NOT NULL,
grade INT,
PRIMARY KEY (sno, cno)
);
2.使用T-SQL创建表SC3,包含sno、cno、grade字段,并在sno和cno两列上建立表级主键约束,将其命名为pk_sc。利用insert语句进行检查。
CREATE TABLE SC3 (
sno CHAR(10) NOT NULL,
cno CHAR(10) NOT NULL,
grade INT,
CONSTRAINT pk_sc PRIMARY KEY (sno, cno)
);
插入检查:
INSERT INTO SC3 VALUES ('001', '001', 80);
INSERT INTO SC3 VALUES ('001', '002', 90);
INSERT INTO SC3 VALUES ('002', '001', 85);
INSERT INTO SC3 VALUES ('002', '002', 95);
SELECT * FROM SC3;
3.应用Management Studio对表设置主键,方法参考下图。
4.使用T-SQL创建表SC4,在成绩字段设置唯一约束,并将其命名为uk_成绩。利用insert语句进行检查。
CREATE TABLE SC4 (
grade INT,
CONSTRAINT uk_ UNIQUE (GRADE)
);
INSERT INTO SC4 VALUES (80);
INSERT INTO SC4 VALUES (90);
INSERT INTO SC4 VALUES (85);
INSERT INTO SC4 VALUES (95);
5.使用T-SQL创建表SC5,学号字段非空,参照学生表学号的取值,课程号参照课程表中课程号的取值。(外键约束)
CREATE TABLE SC5(
SNO INT NOT NULL,
CNO int foreign key references COURSE(CNO))
6. 使用T-SQL创建表SC6,要求grade字段的取值在50到100之间。(使用check约束)
CREATE TABLE SC6(
GRADE INT
CHECK (GRADE>50 AND GRADE<100))
SELECT *
FROM SC6
7. 在查询窗口中输入删除SC4表中的唯一性约束的SQL语句,并执行。
ALTER TABLE sc4
DROP CONSTRAINT uk_
8.使用T-SQL语句为Student表创建一个触发器“testtriggera”,当在表中插入一条新记录时,触发该触发器,输出语句“testtriggera触发器被调用”。
create trigger testtriggera
on student
for insert as
begin
print 'testtriggera触发器被调用'
end
insert into student (sno,sname) values (009,'zhangsan')
9.使用T-SQL语句为Student表创建一个触发器“testtriggerb”,当更新student表时,触发该触发器,输出语句“更新触发器被调用”。
create trigger testtriggerb on student for update as
begin
print '更新触发器被调用'
end
update student set sdept='MA' where sno=95001
10.使用T-SQL语句为Student表创建一个触发器“testtriggerc”,当删除记录时,触发该触发器,输出语句“testtriggerc触发器被调用”。
create trigger testtriggerc on student for delete as
begin
print 'testtriggerc触发器被调用'
end
delete from student where sno=95001
11.在Student表中建立触发器“after_delete_stu”,当删除表中学生记录时,该同学的选课信息一并删除。
CREATE TRIGGER after_delete_stu
ON dbo.Student
AFTER DELETE
AS
BEGIN
SELECT * FROM SC
WHERE Sno=(SELECT Sno FROM deleted)
SELECT * FROM deleted
DELETE FROM SC
WHERE Sno=(SELECT Sno FROM deleted)
SELECT * FROM SC
END
delete from student where sno=95001