數據庫表新增觸發器

https://www.cnblogs.com/hoojo/archive/2011/07/20/2111316.htmlhtml

以上是不錯的數據庫觸發器博客,下面是我本身整理的一些,關於修改了表字段後,作一些判斷的觸發數據庫

USE [Test]htm

GOblog

/****** Object: Table [dbo].[TestTrigger] Script Date: 2018/2/7 下午 02:47:29 ******/
SET ANSI_NULLS ON
GOip

SET QUOTED_IDENTIFIER ON
GO博客

CREATE TABLE [dbo].[TestTrigger](
[ID] [INT] IDENTITY(1,1) NOT NULL,
[TestInt] [INT] NULL,
[TestNvarchar] [NVARCHAR](50) NULL,
[TestDate] [DATETIME] NULL,
CONSTRAINT [PK_TestTrigger] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]變量

GOobject

 

 

--建立insert插入類型觸發器
if (object_id('tgr_TestTrigger_insert', 'tr') is not null)
drop trigger tgr_TestTrigger_insert
go
create trigger tgr_TestTrigger_insert
on TestTrigger
for insert --插入觸發
as
--定義變量
declare @ID int, @TestInt int, @TestNvarchar NVARCHAR(50),@TestDate DATE;
--在inserted表中查詢已經插入記錄信息
select @ID = ID, @TestInt = TestInt,@TestNvarchar=TestNvarchar,@TestDate=TestDate from inserted;
IF(@TestNvarchar=N'b')
BEGIN
INSERT INTO [dbo].[TestTriggerStory](TestInt,TestNvarchar,TestDate) SELECT TestInt,TestNvarchar,TestDate FROM inserted;
END

go
--建立insert插入類型觸發器
if (object_id('tgr_TestTrigger_update', 'tr') is not null)
drop trigger tgr_TestTrigger_update
go
create trigger tgr_TestTrigger_update
on TestTrigger
for update --插入觸發
ASdate

--定義變量
declare @ID int, @TestInt int, @TestNvarchar NVARCHAR(50),@TestDate DATE,
@IDNew int, @TestIntNew int, @TestNvarcharNew NVARCHAR(50),@TestDateNew DATE;
--查看更新前的數據
select @ID = ID, @TestInt = TestInt,@TestNvarchar=TestNvarchar,@TestDate=TestDate FROM Deleted ;
--PRINT @TestNvarchar
IF(@TestNvarchar<>N'b')
BEGIN
PRINT '觸發了1'
select @IDNew = ID, @TestIntNew = TestInt,@TestNvarcharNew=TestNvarchar,@TestDateNew=TestDate FROM inserted ;
IF(@TestNvarcharNew=N'b')
BEGIN
INSERT INTO [dbo].[TestTriggerStory](TestInt,TestNvarchar,TestDate) SELECT TestInt,TestNvarchar,TestDate FROM inserted;
PRINT '觸發了2'
END
END
select

 

INSERT INTO dbo.TestTrigger
( TestInt, TestNvarchar, TestDate )
VALUES ( 0, -- TestInt - int
N'b', -- TestNvarchar - nvarchar(50)
GETDATE() -- TestDate - datetime
)

 

SELECT * FROM dbo.TestTrigger

UPDATE dbo.TestTrigger SET TestNvarchar=N'b' WHERE ID=1

相關文章
相關標籤/搜索