在字段上创建事务和触发器

时间:2014-12-12 09:08:02

标签: sql-server vb.net

请在vb.net和sql server中新建,我在数据库中创建了一个名为Service and Trans的两个表。

Create Table Service(
ServiceID int,
ServiceName varchar(30),
ServiceStartValue int
);

Create Table Trans(
EntryTS datetime,
EntryCounter int,
ServedTS datetime,
ServedCounter int,
Skipped int
);

我正在尝试创建一个'交易并触发'将根据ServiceID上的EntryCounter中的值检查和更新ServedCounter,更新语句不得允许ServedCounter> EntryCounter。

2 个答案:

答案 0 :(得分:0)

我不太了解完整的要求,但是这里有一些方法可以阻止更新(或插入)触发器的发生。

CREATE TRIGGER Trans_upd_trg ON Trans AFTER INSERT, UPDATE
AS 
BEGIN
SET NOCOUNT ON;

--Don't allow the update
IF EXISTS(SELECT 1 FROM inserted WHERE ServedCounter > EntryCounter)
    RAISERROR ('ServedCounter > EntryCounter', 16,  1 );
END
GO

在触发器的上下文中,您有两个逻辑表,INSERTED和DELETED。 这些表包含旧值和新值。 (对于插入操作,删除为空)

希望有所帮助。

答案 1 :(得分:0)

使用Instead Of Trigger

CREATE TRIGGER Trans_upd_trg
ON Trans
Instead OF INSERT, UPDATE
AS
  BEGIN
      SET NOCOUNT ON;

      IF EXISTS (SELECT *
                 FROM   inserted
                 WHERE  ServedCounter > EntryCounter)
         AND EXISTS (SELECT *
                     FROM   deleted)
        UPDATE A
        SET    EntryTS = I.EntryTS,
               EntryCounter = I.EntryCounter,
               ServedTS = I.ServedTS,
               ServedCounter = I.ServedCounter,
               Skipped = I.Skipped
        FROM   Trans A
               JOIN inserted I
                 ON A.EntryTS = I.EntryTS
                    AND A.ServedTS = I.ServedTS
        WHERE  i.ServedCounter > i.EntryCounter
      ELSE
        INSERT INTO Trans
        SELECT *
        FROM   inserted
        WHERE  ServedCounter > EntryCounter
  END

GO