Click here to Skip to main content
15,881,380 members
Articles / Web Development / ASP.NET
Alternative
Tip/Trick

Sqlserver Trigger a quick look

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
22 Apr 2011CPOL 4.8K   1  
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)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --