Do this with relational integrity - use NOT using triggers, because they are always a real pain to maintain after that (they have their place, not here). The integrity of the relationship will do everything you need.
Using relational integrity can be quite elegant, but what you need to do is slightly counterintuitive, so it's easy to skip.
Create the main table of the tblMain table using a numeric primary key. For simplicity, I checked this with a single-column table, intID, and I populated it with values โโof 0.1 and 2.
Then create a second tblGuard table with the same numeric primary key. I added one row to this table, value 1.
Now a bit of inverse logic. Create a foreign key in the tblGuard table that references the tblMain table
ALTER TABLE [dbo].[tblGuard] ADD CONSTRAINT [FK_tblGuard_tblMain] FOREIGN KEY ( [intID] ) REFERENCES [dbo].[tblMain] ( [intID] )
The restriction ensures that a row with intID 1 cannot be deleted from the tblMain table, because the tblGuard table referential integrity requires that a value of 1 exist in tblMain. This works with deletion and truncation.
Cruachan
source share