SQL 2008 怎么实现删除学生表里面的一条记录,成绩表里面关于这个学生的记录也同时删掉,谢求具体代码
2个回答
2015-04-08
展开全部
-- 按照注释一步步执行 看效果
--创建表
IF OBJECT_ID('tstudent') > 0
DROP TABLE tstudent
GO
CREATE TABLE tstudent
(
fstudentno VARCHAR(10) PRIMARY KEY ,
fname NVARCHAR(10),
)
IF OBJECT_ID('tScore') > 0
DROP TABLE tScore
CREATE TABLE tScore
(
fstudentno VARCHAR(10) PRIMARY KEY ,
fscroe INT
)
GO
--插入测试数据
INSERT dbo.tstudent
( fstudentno, fname )
VALUES ( '001', -- fstudentno - varchar(10)
N'小张' -- fname - nvarchar(10)
)
INSERT dbo.tScore
( fstudentno, fscroe )
VALUES ( '001', -- fstudentno - varchar(10)
90 -- fscroe - int
)
--查看插入效果
SELECT *
FROM dbo.tScore
SELECT *
FROM dbo.tstudent
--创建触发器
if (object_id('tgr_DeleteByStudentNo', 'tr') is not null)
drop trigger tgr_DeleteByStudentNo
Go
--创建一个删除的触发器
CREATE trigger tgr_DeleteByStudentNo ON tstudent
AFTER DELETE
as
DECLARE @strStudentNo VARCHAR(10)
SELECT @strStudentNo = fstudentno FROM deleted
DELETE FROM tScore WHERE fstudentno = @strStudentNo
DELETE FROM tstudent WHERE fstudentno = '001'
--查看删除效果
SELECT *
FROM dbo.tScore
SELECT *
FROM dbo.tstudent
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询