SQL(触发器)

时间:2022-10-31 07:52:01

触发器语法格式(实例):

ALTER TRIGGER tri_edituser
ON dbo.sys_User
FOR INSERT,UPDATE,DELETE
AS
BEGIN
---判断是新增?修改?删除?
DECLARE
@IsInsert BIT,
@IsUpdate BIT,
@IsDelete BIT
IF EXISTS(SELECT 1 FROM inserted) AND NOT EXISTS(SELECT 1 FROM deleted)
SET @IsInsert = 1
ELSE
SET @IsInsert = 0
IF EXISTS(SELECT 1 FROM inserted) AND EXISTS(SELECT 1 FROM deleted)
SET @IsUpdate = 1
ELSE
SET @IsUpdate = 0
IF NOT EXISTS(SELECT 1 FROM inserted) AND EXISTS(SELECT 1 FROM deleted)
SET @IsDelete = 1
ELSE
SET @IsDelete = 0

---新增
IF(@IsInsert=1)
BEGIN
--获取工号
DECLARE @ID VARCHAR(20)
IF EXISTS(Select * From tab_User Where RecordDate > DATEADD(day,DATEDIFF(day,0,getdate()),0))
BEGIN
SELECT @ID=CAST(MAX(工号) as int) + 1 From tab_User Where RecordDate > DATEADD(day,DATEDIFF(day,0,getdate()),0)
END
ELSE
BEGIN
SELECT @ID=CONVERT(varchar(8),getdate(),112) + '01'
END

INSERT INTO ERPDB.dbo.tab_user
(
-- ID -- this column value is auto-generated
工号,
用户名,
密码,
角色,
二级权限,
employee_mail,
mobile,
dept,
isVisible,
lookContractRight,
RecordDate
)
SELECT @ID,UserName,'888888','',
'销售查询(个人),费用查询(个人),应收款项(个人),询价查询(个人),进出货查询(个人),利息查询(个人),外借查询(个人),',
Email,NULL,NULL,1,@ID,GETDATE() FROM INSERTED
END
---修改
IF(@IsUpdate = 1)
BEGIN
SELECT @ID = 工号 FROM ERPDB.dbo.tab_user AS tu JOIN INSERTED i ON tu.用户名=i.UserName
IF (@ID IS NOT NULL AND @ID <> '')
BEGIN
UPDATE ERPDB.dbo.tab_user
SET
-- ID = ? -- this column value is auto-generated
用户名 = i.UserName,
employee_mail = i.Email,
isVisible = i.[Status],
RecordDate = GETDATE()
FROM ERPDB.dbo.tab_user tu,INSERTED i,DELETED d
WHERE tu.用户名=i.UserName AND tu.工号=@ID
END
END
IF(@IsDelete = 1)
END

--ALTER TABLE sys_User DISABLE TRIGGER tri_edituser