Question

I am developing a database to track the movement of objects throughout a manufacturing process. Currently I have a "live" table of what is currently in the process at the moment, including the current location of where it is (tLiveTable)

tLiveTable:

PieceID   TimeStamp            LocationRef
------------------------------------------
30        03/12/2012 09:16:26       8

When a PieceID moves to a new location, we perform an UPDATE which updates the LocationRef to the new location, and updates the timestamp with GetDate().

However, for a historical view of where the PieceIDs were in the past, I have also created a tracking table (tPieceTracking)

tPieceTracking:

PieceID   TimeStamp            LocationRef      InOut
-----------------------------------------------------
30        03/12/2012 09:11:34       1             1
30        03/12/2012 09:12:13       1             0
30        03/12/2012 09:14:27       2             1
30        03/12/2012 09:15:01       2             0
30        03/12/2012 09:16:26       8             1

InOut meaning: 1 = entered that location, 0 = left that location

My original plan was to INSERT a new record into tPieceTracking manually each time the PieceID moves around.

My question is, could I use database triggers or some other type of scripting within SQL 2005 SP3 so that the database can perform this tracking automatically (so that my application isn't responsible for doing it)?

I've looked into database triggers but the first stumbling block I've encountered is that MSSQL apparently doesn't support BEFORE UPDATE, which I think is what I'd need to trigger on.

Any help would be appreciated.

Was it helpful?

Solution

CREATE TRIGGER trig ON tLiveTable AFTER UPDATE
AS
     INSERT INTO tPieceTracking select t.PieceID, getdate(), PrevLocation, 0
     FROM UPDATED t
     INNER JOIN
    (
        SELECT MAX(LocationRef) as PrevLocation, PieceID
        FROM tPieceTracking
        GROUP BY PieceID
    ) p on p.PieceID = t.PieceID

     INSERT INTO tPieceTracking select t.PieceID, getdate(), LocationRef, 1
     FROM UPDATED t

Something like that? I think in SQL Server you actually have to use INSERTED and DELETED to work out what has been updated (instead of "UPDATED")

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top