我是在数据库中使用触发器的新手,我创建了一些对我来说效果很好的触发器,除了当我尝试创建一个在删除一行后将显示一条消息的触发器时。
我尝试使用此代码:
ALTER TRIGGER "mycustomerTrigger" AFTER delete ON customers FOR EACH ROW BEGIN ATOMIC print 'trigger is working' END
当我创建此触发器时,它不会给出错误消息,但是当我删除一行时,它不会显示我打印的消息。
这是因为触发器的运行方式,基本上它不在查询执行窗口中。一种方法是登录到事件查看器。
Create trigger TestTrigger on tablefortrigger for insert as –Declare variable to hold message Declare @Msg varchar(8000) –Assign to message “Action/Table Name/Time Date/Fields inserted set @Msg = ‘Inserted | tablefortrigger | ‘ + convert(varchar(20), getdate()) + ‘ | ‘ +(select convert(varchar(5), track) + ‘, ‘ + lastname + ‘, ‘ + firstname from inserted) –Raise Error to send to Event Viewer raiserror( 50005, 10, 1, @Msg)
执行此操作的另一种方法是写入文件,这里当然存在权限问题,但是您可以执行以下操作:
Alter trigger TestTrigger on tablefortrigger for insert as Declare @Msg varchar(1000) –Will hold the command to be executed by xp_cmdshell Declare @CmdString varchar (2000) set @Msg = ‘Inserted | tablefortrigger | ‘ + convert(varchar(20), getdate()) + ‘ — ‘ +(select convert(varchar(5), track) + ‘, ‘ + lastname + ‘, ‘ + firstname from inserted) –Raise Error to send to Event Viewer raiserror( 50005, 10, 1, @Msg) set @CmdString = ‘echo ‘ + @Msg + ‘ >> C:logtest.log’ –write to text file exec master.dbo.xp_cmdshell @CmdString