my first sql server trigger

November 17, 2003

This took me surprisingly long to figure out…

First create two tables for the test:

CREATE TABLE TriggerTestOne (
  Name varchar 50,
  AdditionalField varchar 50
)


CREATE TABLE TriggerTestTwo (
  Name varchar 50,
  LogEntry varchar 256,
  Action varchar 100
)

Then create the following trigger:

CREATE TRIGGER TestLog ON TriggerTestOne
FOR UPDATE
AS
if update(AdditionalField)
  insert into
    TriggerTestTwo (Action, Name, LogEntry)
    select 'remove', del.Name , del.AdditionalField from deleted del
  insert into
    TriggerTestTwo (Action, Name, LogEntry)
    select 'added', ins.Name , ins.AdditionalField from inserted ins

This will log all values changes in the AdditionalField column in TriggerTestOne into TriggerTestTwo.

The tricky part for me was trying to dig through the manuals to discover the delelted and inserted tables.

Entry Filed under: programming. .

2 Comments Add your own

  • 1. fjj  |  November 17, 2003 at 4:29 pm

    I’ve my notes if you wanted help. :)

    Reply
  • 2. Imran Sohail  |  March 18, 2005 at 8:51 am

    Dear Friend
    I did same as you mentioned above very First trigger with in TriggerTestone and TriggerTestTwo Table. when i create trigger i got syntax Succesfully but when i saved and pressed okay button then i got this error message “Error 21001:[SQL-DMO]Stored Procedure Definition” .
    can u tell me that how i can access and see changes using this trigger. i m using ASP and SQL Server 2000. My objective is i have value in Table 1 and that value want to insert Table2 when any changes occur in Table1.
    How i can use this Trigger. Please help me

    Imran Sohail
    Software Engieer
    Karachi Stock Exchange

    Reply

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe to the comments via RSS Feed


About me

Hello, I'm Nathan Jacobs and you are looking at my blog. I am a doctoral candidate in Computer Science at Washington University in St. Louis focusing on Computer Vision. My research is in algorithms to improve the ability of computer to reason about the natural world. I also really like to make attractive and informative visualizations of complex data.

I currently update my flickr site much more frequently than this blog.

RSS twitter

Category Cloud

computer vision friend information retrieval information technology knowledge management landscaping machine learning math mozilla noise personal programming research site admin social software teaching travel ultimate frisbee usability web standards

friend

links

papers

Top Posts

Flickr Photos

Smooth

View from Mill Club 405

View from Mill Club 405

Rainbow Sunrise

Why can't I turn left?

More Photos