當前位置:首頁 » 編程語言 » sql修改觸發

sql修改觸發

發布時間: 2023-11-22 20:43:33

Ⅰ SQL求助 插入刪除修改的觸發器代碼編寫

---創建測試表:
Create Table MyTest(
id int identity(1,1) not null primary key,
[name] varchar(100) null
)
--創建觸發器:
CREATE TRIGGER trigtest--創建觸發器trigtest
ON mytest--在表mytest上建
for INSERT,DELETE,UPDATE--為插入,刪除,修改
AS
BEGIN
declare @a int,
@b int,
@id int,
@name varchar(100),
@oldId int,--原ID號
@oldName varchar(100)--原來的name
set @a=0
set @b=0
if exists(select * from inserted)--如果存在插入新的數據則設置@a=1
begin
set @a=1
end
if exists(select * from deleted)--如果存在刪除數據則設置@b=1
begin
set @b=1
end
if (@a=1)and(@b=0)--新增:當插入表inserted存在數據而刪除表deleted不存數據時,為新增操作。
begin
select @id=id,@name=name from inserted
print '增加了ID號為【'+cast(@id as varchar(5))+'】Name為【'+@name+'】的數據!'
end
if (@a=1)and(@b=1)--修改:當插入表insertedt和刪除表deleted都存在數據時,為修改操作。
begin
select @id=id,@name=name from inserted
select @id=id,@oldname=name from deleted
print '修改了ID號為【'+cast(@id as varchar(5))+'】的數據Name由【'+@oldname+'】變為【'+@name+'】'
end
if (@a=0)and(@b=1)--刪除:當插入表inserted不存在數據而刪除表deleted存在數據時,為刪除操作。
begin
select @id=id,@name=name from deleted
print '刪除了ID號為【'+cast(@id as varchar(5))+'】Name為【'+@name+'】的數據!'
end
END

熱點內容
android獲取數組 發布:2025-08-22 02:24:04 瀏覽:645
徵型壓縮機 發布:2025-08-22 02:10:15 瀏覽:494
真空壓縮袋能上飛機嗎 發布:2025-08-22 02:10:01 瀏覽:94
怎麼刪除伺服器文件 發布:2025-08-22 02:04:07 瀏覽:168
爐石傳說威脅腳本投降 發布:2025-08-22 01:54:10 瀏覽:331
大大哇腳本 發布:2025-08-22 01:49:32 瀏覽:94
python2pip 發布:2025-08-22 01:48:56 瀏覽:388
php和null 發布:2025-08-22 01:48:49 瀏覽:964
安卓手機怎麼強制解鎖 發布:2025-08-22 01:48:48 瀏覽:81
安卓422怎麼樣 發布:2025-08-22 01:48:48 瀏覽:625