[SQL]insert、update 表觸發器應用的demo

--建立測試表
create table student
(
    stu_id int
    ,libraryCardNo varchar(10)
)

create table borrowbook
(
    b_id int
    ,libraryCardNo varchar(10)
)

GO

--插入測試數據
insert student
select 1,'221'
insert borrowbook
select 1,'221'

GO

--查詢數據
SELECT * FROM  student
SELECT * FROM borrowbook 


--建立觸發器<更新表>
create  trigger stu_trg
on student 
for update
as
    declare @a varchar(100)
           ,@b varchar(100)
           
           select @a=libraryCardNo ,@b=stu_id from inserted
           update borrowbook set libraryCardNo=@a where b_id=@b


GO
--建立觸發器<插入表>
create trigger insert_trg
on student
for insert
as 
    declare @a varchar(100)           
           ,@b varchar(100)
           select @a=libraryCardNo ,@b=stu_id from inserted
           insert into borrowbook(b_id,libraryCardNo)values(@b,@a)
          

GO

--*********測試結果-----------------更改數據
update student set libraryCardNo='999' where stu_id=1
insert into student(stu_id,libraryCardNo)values(3,'3000')
--結果對比
select * from student 
select * from borrowbook 
相關文章
相關標籤/搜索