Click here to Skip to main content
15,885,435 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey guys, I'm really bad/new at T-SQL but I need it for a project I'm working on.

What I want to do here is to be able to populate a table (logs) with date from another table (events) when this is updated (essentially making a log).

I have this pseudocode:

SQL
CREATE TRIGGER [dbo].[EventUpdate]
   ON  [dbo].[Events]
   AFTER UPDATE
AS
BEGIN
    SET NOCOUNT ON;

    WHILE tablesupdated.hasNext()
    BEGIN
        [dbo].[Logs].[date] = dateTime.Now();
        [dbo].[Logs].[user] = "John";
        [dbo].[Logs].[changes] = [dbo].[Events].[updatedTable].previousval() + "-->" + [dbo].[Events].[updatedTable].afterval();
        [dbo].[Logs].[eventId] = [dbo].[Events].[id];
    END
END
GO


It's more to give you an idea of what I want and how bad I am at this... can you guys help please?

PS: I'm completely open to new suggestion on how to get this done.
Posted
Updated 9-Mar-15 23:58pm
v2
Comments
Kornfeld Eliyahu Peter 10-Mar-15 6:02am    
Are you want to keep a data history upon update?
varmartins 10-Mar-15 6:03am    
I didn't understand the question sorry. But what I want is for whenever a value(s) is updated on the table Events the changes are recorded on Logs
John C Rayan 10-Mar-15 6:15am    
Hi look at the solution 2 which is what you need. replace the columnname with your column or columnlist.

SQL
CREATE TRIGGER [dbo].[EventUpdate]
   ON  [dbo].[Events]
   AFTER UPDATE
AS
BEGIN
       SET NOCOUNT ON;

       INSERT INTO [dbo].Logs([date],[user],[changes],[eventId])
             SELECT getdate(), 'john', I.columnname + '-->' + D.columnname, I.id
             FROM Inserted I
                  INNER JOIN Deleted D ON I.id = D.id

END
GO
 
Share this answer
 
Comments
varmartins 10-Mar-15 6:27am    
Thanks mate ;)
Within a trigger there are a pair of conceptual tables called "inserted" and "deleted" which contains the records that are being updated (new and previous data). (See CREATE TRIGGER[^] documentation - it has an audit example included).

You need to iterate through the rows in this pair of tables and log them to the table.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900