Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Sqlserver Trigger a quick look

0.00/5 (No votes)
22 Apr 2011CPOL 5K  
This article demonstrates the #1 failure when people write triggers.When writing SQL triggers you can NEVER be sure that you will ONLY have one record when processing the trigger results.In Your example only the first record from the INSERTED table will be captured, or worse random bits...
This article demonstrates the #1 failure when people write triggers.
When writing SQL triggers you can NEVER be sure that you will ONLY have one record when processing the trigger results.
In Your example only the first record from the INSERTED table will be captured, or worse random bits through out will be logged as a single record.

SQL
Insert into Usertable ([name])
Values ('Bob'),
       ('Luke'),
       ('Frank'),
       ('James');


Your trigger would only capture Bob.
In order to fix this you need to write a cursor, or a CTE, or in this case your not actually performing any real work, you can do this.
SQL
INSERT INTO [TestDb].[dbo].[tt]
SELECT
 [ID],
 [Name],
 'Inserted Record -- After Insert'
FROM INSERTED


This actually simplifies your example as it doesn't require numerous variables to store values.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)