1. 程式人生 > 實用技巧 >SQL Server Trigger Example

SQL Server Trigger Example

--檢視資料庫中所有觸發器 https://docs.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql?view=sql-server-ver15
-- 塗聚文(Geovin Du) edit  https://www.mssqltips.com/sqlservertip/5909/sql-server-trigger-example/
select * from sysobjects where xtype='TR'
--
exec sp_helptext 'TriClerkOfficeInsert'


--建立insert插入型別觸發器 PositionRoleDefaut ,當新增工員資料,在角色表中的新增
if (object_id('TriClerkOfficeInsert', 'tr') is not null)
    drop trigger TriClerkOfficeInsert
go
create trigger TriClerkOfficeInsert
on ClerkOffice -- 指定建立觸發器的表
    for insert --插入觸發
as
    --定義變數
    declare @id uniqueidentifier, @DefaultRoleId int, @PositionId int;
    --在inserted表中查詢已經插入記錄資訊
    select @id = ClerkId, @PositionId = ClerkPosition from inserted;
    select @DefaultRoleId= RoleDefautSet  from PositionRoleDefaut where RolePositionId=@PositionId
    insert into ClerkOfficeRole(ClerkRoleKey,ClerkRoleSet) values(@id,@DefaultRoleId)
    print '新增成功!';
go

--修改時觸發器
if (object_id('TriClerkOfficeUpdate', 'tr') is not null)
    drop trigger TriClerkOfficeUpdate
go
create trigger TriClerkOfficeUpdate
on ClerkOffice -- 指定建立觸發器的表
    for update --修改時觸發
as
    --定義變數
    declare @id uniqueidentifier, @DefaultRoleId int, @PositionId int,@ClerkName nvarchar(100),@OldClerkName nvarchar(100);
   --更新前的資料
    --select @id = ClerkId,@OldClerkName=ClerkName,@PositionId=ClerkPosition from deleted;  -- 修改前的資料就存在 deleted 這個表中

	 --if (exists (select * from ClerkOffice where ClerkName like '%'+ @OldClerkName + '%'))
       -- begin
		 --更新後的資料
		select @id = ClerkId,@ClerkName=ClerkName,@PositionId=ClerkPosition from inserted;-- 修改後的資料就存在 inserted 這個表中
	 --end
    --select @id = ClerkId, @PositionId = ClerkPosition from ClerkOffice;
    select @DefaultRoleId= RoleDefautSet  from PositionRoleDefaut where RolePositionId=@PositionId;
	if(exists (select * from ClerkOfficeRole where ClerkRoleKey=@id))
	begin
    update ClerkOfficeRole set ClerkRoleSet=@DefaultRoleId where ClerkRoleKey=@id;
	end
	else
	begin
	 insert into ClerkOfficeRole(ClerkRoleKey,ClerkRoleSet) values(@id,@DefaultRoleId);
	end
    print '修改成功!';
go




--delete刪除型別觸發器
if (object_id('TriClerkOfficeDelete', 'TR') is not null)
drop trigger TriClerkOfficeDelete
go
create trigger TriClerkOfficeDelete
on ClerkOffice
    for delete --刪除觸發
as    
   declare @id uniqueidentifier
    select @id=ClerkId from deleted;
    delete ClerkOfficeRole where ClerkRoleKey=@id;
    print '刪除資料成功!';
go