我正在编写一个触发器来审计 MySQL 数据库。IF 语句不起作用。我在哪里做错了?
另外,您能否指导我了解 mysql 审计的最佳触发器。
DELIMITER $$
CREATE
DEFINER = 'sqlsa'@'%'
TRIGGER AuthenticationLog_U
AFTER UPDATE
ON AuthenticationLog
FOR EACH ROW
BEGIN
DECLARE Type varchar(1);
DECLARE TableId tinyint;
DECLARE IsActive tinyint;
SET @Type='U';
SET @TableId = 2;
SET @IsActive = (SELECT IsActive FROM AuditDB.ExportLogTableDefinition WHERE TableId=@TableId);
IF (@IsActive=1) THEN
INSERT INTO AuditDB.ExportLog (DBName,TableId,OperationType,HostName,UserName,PrimaryKey,OldData,NewData)
VALUES (DATABASE(),@TableId,@Type,@@hostname,CURRENT_USER(),OLD.PKAuthenticationLogID,
CONCAT_WS('',
'[Key]=',IFNULL(OLD.Key,'NULL')
,'[Secret]=',IFNULL(OLD.Secret,'NULL')
,'[Token]=',IFNULL(OLD.Token,'NULL')
,'[ApplicationId]=',IFNULL(OLD.ApplicationId,'NULL')
,'[IpAddress]=',IFNULL(OLD.IpAddress,'NULL')
,'[Message]=',IFNULL(OLD.Message,'NULL')
,'[CreatedOn]=',IFNULL(OLD.CreatedOn,'NULL')
,'[IsSuccess]=',IFNULL(EXPORT_SET(OLD.IsSuccess,'1','0','',1),'NULL')
,'[LogType]=',IFNULL(OLD.LogType,'NULL')
),
CONCAT_WS('',
'[Key]=',IFNULL(NEW.Key,'NULL')
,'[Secret]=',IFNULL(NEW.Secret,'NULL')
,'[Token]=',IFNULL(NEW.Token,'NULL')
,'[ApplicationId]=',IFNULL(NEW.ApplicationId,'NULL')
,'[IpAddress]=',IFNULL(NEW.IpAddress,'NULL')
,'[Message]=',IFNULL(NEW.Message,'NULL')
,'[CreatedOn]=',IFNULL(NEW.CreatedOn,'NULL')
,'[IsSuccess]=',IFNULL(EXPORT_SET(NEW.IsSuccess,'1','0','',1),'NULL')
,'[LogType]=',IFNULL(NEW.LogType,'NULL'))
);
END IF;
END
$$
DELIMITER ;
没有错误信息。但我尝试查询,干得好。
SET @IsActive = 1;
IF (@IsActive=1) THEN
经过一些实验,我发现如果我不在变量名前面加上“@”前缀,代码就可以工作: