Image of Navigational Panel mapped to Contents / Home / Search Creating a SQL Server Counter Field
Tech Support Contribution

Image of Line Break

The Code...
The idea behind my logic is to let users or processes put a value in the counter field, or leave it NULL, but the INSERT TRIGGER would make it equal to the record count. The UPDATE TRIGGER will protect the field from being changed to an invalid value. . .

HERE IT IS . . . . .

  CREATE TABLE aaaa (
    aaa char (  3 )  NULL,
    bbb char (  3 )  NULL,
    zCount int NULL
   )
  GO

  CREATE  UNIQUE  INDEX zkey ON aaaa
    ( zCount )
  GO

  CREATE TRIGGER aaaaIns ON dbo.aaaa FOR INSERT  AS
  BEGIN
   /* No matter what is entered, the zCount will be set to the record
      count */
   IF (Select zCount from inserted) Is Not NULL
    update aaaa
    set zCount = (Select Count(*) from aaaa)
    where zCount = (Select zCount from inserted)
   ELSE
    update aaaa
    set zCount = (Select Count(*) from aaaa)
    where zCount Is Null
  END
  GO

  CREATE TRIGGER aaaaUpd ON dbo.aaaa FOR UPDATE  AS
  BEGIN
  /* If any attempt to change zCount to something other than the record count
     the transaction will be rolled back.  Keeping in mind that the insert 
     trigger will also trigger the update trigger */
  If (Select zCount from inserted)  (Select Count(*) from aaaa)
  BEGIN
     RAISERROR 600225 'Trigger aaaaUpd on table dbo.aaaa:  Not allowed to update
  zCount.
     ROLLBACK TRANSACTION
     RETURN
  END
  END
  GO

Name: John Holland
Email: john.holland@exim.gov


Image of Arrow to Previous Article Image of Arrow to Next Article

[TECH SUPPORT TOC]
Image of Line Break
[HOME] [TABLE OF CONTENTS] [SEARCH]