我是在数据库中使用触发器的新手,我创建了一些对我来说非常好的触发器,除了当我尝试创建一个在删除行后显示消息的触发器时。
我尝试使用此代码:
ALTER TRIGGER "mycustomerTrigger"
AFTER delete ON customers
FOR EACH ROW
BEGIN ATOMIC
print 'trigger is working'
END
当我创建此触发器时,它不会给出错误消息,但是当我删除一行时,它不会显示我打印的消息。
答案 0 :(得分:5)
这是因为触发器的运行方式,基本上它不在查询执行窗口中。一种方法是登录事件查看器。
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
可在此处找到更多信息:http://www.sql-server-performance.com/2005/log-file-trigger/
答案 1 :(得分:1)
如果您希望以轻量级的方式进行操作,而无需查看服务器日志,引发错误或设置特殊权限,则只需创建一个表即可为日志保留一列:
create table logs (logstring nvarchar(max))
并这样登录:
insert into logs
values ('hello')