为Speific Column创建触发器

时间:2015-04-22 17:19:46

标签: sql-server triggers

尝试为特定列创建触发器但是只能触发整个表的工作。

  Create Trigger Nameblock on tblcustomer
  For Insert
  As
  Begin
  rollback transaction
  print 'Name edit not allowed!'
  End

我想要它所以只有在完成对CustomerName的更新时才会创建触发器,这是表中的一列

2 个答案:

答案 0 :(得分:1)

Create Trigger Nameblock on tblcustomer
For Update
As
if UPDATE(name)
Begin
  rollback transaction
  RAISERROR('Name edit not allowed!',16,1)
End

覆盖评论点,您也可以使用以下触发器。

Create Trigger Nameblock on tblcustomer
INSTEAD OF UPDATE
As
Begin
  UPDATE tblcustomer set phone=I.phone,address=I.adress 
  from INSERTED I inner join tblcustomer on (tblcustomer.id=I.id)
  where I.name=tblcustomer.name

  if UPDATE(name)
      print 'Name edit not allowed!'
END

答案 1 :(得分:0)

看起来你非常接近。添加IF UPDATE(CustomerName)应该这样做:

CREATE TRIGGER Nameblock ON tblcustomer
FOR UPDATE --change this to update instead of insert
AS
BEGIN
    IF UPDATE (CustomerName)  --Add this line to your query
    BEGIN
    rollback transaction
    print 'Name edit not allowed!'
    END 
END
GO