为插入行和删除行创建触发器

时间:2014-11-11 16:56:14

标签: sql-server triggers sql-insert sql-delete

我正在尝试为插入行以及删除行创建触发器。如果插入了一行,则print语句将给出一条消息,如果删除了一行,则print语句将给出另一条消息。我的老师使用了这个例子,但是使用了DDL语句而不是我输入的DML语句。我的问题是我如何获得等价物,但是这样做DML语句可以工作吗?到目前为止,我的输出显示了else print语句是否插入或删除了行。我根本没有相信它甚至会对插入语句进行计数。

这是我的架构。

CREATE TABLE dbo.Customers
(
    CustomerID          INT             NOT NULL IDENTITY PRIMARY KEY,
    CustomerFName       VARCHAR(30)     NOT NULL,
    CustomerLName       VARCHAR(30)     NOT NULL,
    CustomerAddress1    VARCHAR(50)     NOT NULL,
    CustomerAddress2    VARCHAR(50)     NULL,
    CustomerCity        VARCHAR(50)     NOT NULL,
    CustomerState       CHAR(2)         NOT NULL,
    CustomerZipCode     INT             NOT NULL,
    CustomerHome        VARCHAR(20)     NOT NULL,
    CustomerCell        VARCHAR(20)     NOT NULL,
    CustomerEmail       VARCHAR(50)     NULL
);

这是我已有的数据。

CustomerID  CustomerFName   CustomerLName   CustomerAddress1    CustomerAddress2        CustomerCity    CustomerState   CustomerZipCode CustomerHome    CustomerCell        CustomerEmail
1   Jane    Swanson 123 Negley Ave  Apartment #3    Pittsburgh  PA  15222   (412) 555 -     6678    (412) 555 - 6789    jane.swanson@gmail.com
2   Phillip Connely 167 Warble St   NULL    Pittsburgh  PA  15212   (412) 555 - 9463    (412) 555 - 6797    philli123@yahoo.com
3   Alfred  Mansley 41 Wild Place   Apartment #4    Pittsburgh  PA  15205   (412) 555 - 9371    (412) 555 - 4259    mansleyman592@gmail.com
4   Angel   Smith   2050 Morningside Ave    NULL    Pittsburgh  PA  15222   (412) 555 - 6931    (412) 555 - 1135    angie.smith01@hotmail.com
5   Walter  Weezley 2670 Butler St  NULL    Pittsburgh  PA  15210   (412) 567 - 6931    (412) 666 - 1256    walt.disney2012@gmail.com

触发器创建

CREATE TRIGGER Table_Update
   ON Customers
AFTER INSERT, DELETE
AS
    If EXISTS (SELECT 1 FROM inserted)
        PRINT 'The company has gained customers.'
    ELSE
       PRINT 'The company has lost customers.'

测试

INSERT INTO Customers
VALUES('Pter', 'Jackson', '1240 Wlnut St', 'Apartment #1', 'Pittsburgh',
'PA', 15232, '(724) 789 - 1234', '(724) 555 - 8706', 'pete.jack43@yahoo.com');

DELETE Customers
WHERE CustomerFName = 'Pter';

插入一行后,我收到消息:

  

该公司赢得了客户。

     

Msg 2601,Level 14,State 1,Procedure Table_Update,Line 15
  无法在对象' dbo中插入重复的键行。客户'具有唯一索引' IX_CustomerName'。重复键值为(Jackson,Pter)   声明已经终止。

在我删除后立即收到消息:

  

公司失去了客户   (1行受影响)
  (1行受影响)
  (0行(s)受影响)

我想要的输出是添加一行或删除一行。即使我选择删除不存在的行,它似乎也有上述影响。它似乎正在做的是创建多行。我在客户名称上有一个UNIQUE键,因此如果客户出现多次,则会发生错误。如何将输出插入到插入的一行而不是系统尝试多次插入同一行?

1 个答案:

答案 0 :(得分:2)

如何使用特殊表Inserted or Deleted

If exists (select 1 from inserted)
    PRINT 'The company has gained customers.'
ELSE
    PRINT 'The company has lost customers.'