Creating a SQL Server Counter FieldHERE 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