Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Update Trigger

Author  Topic 

FernandoLorival
Starting Member

19 Posts

Posted - 2008-04-21 : 11:48:25
Hi All,
I have a table with 5 rows that represent our production machines, that table is updated every 5 sec by our production software but not all the rows change values although the update runs on every row every time.
Let me try to give an example:

tbl_Machine:

Id | Name | Prod_Count
1 | Press1 | 3
2 | Press2 | 4
3 | Press3 | 0
4 | Press4 | 0
5 | Press5 | 5

After the update:

Id | Name | Prod_Count
1 | Press1 | 4
2 | Press2 | 5
3 | Press3 | 0
4 | Press4 | 0
5 | Press5 | 5

only machine 1 and machine 2 changed values...

I need a trigger to count my production, so I have created a temp table that writes a line every time the update is done, but the problem is that the update is done on every line not just on the ones that change value.
How do I build a trigger to give me just the line that actualy changes the Prod_Count value?

Thank you all for the help.






nr
SQLTeam MVY

12543 Posts

Posted - 2008-04-21 : 11:55:44
create trigger tr on tbl for update
as
insert au_tbl
select i.id, id.name, i.Prod_Count
from inserted i
join deleted d
on i.id = d.id
where i.Prod_Count <> d.Prod_count

Do you want to take into account nulls and inserts and deletes?

==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-04-21 : 11:57:19
You can compare te old and new values inside the trigger and find out those lines that have changed their values.

something like

CREATE TRIGGER YourTrigger
ON YourTable
AFTER UPDATE
AS
BEGIN
IF EXISTS (SELECT *
FROM INSERTED i
INNER JOIN DELETED d
ON d.id=i.id
WHERE i.Prod_count <> d.Prod_Count)
UPDATE temp
SET Count=Count + 1

END
Go to Top of Page

FernandoLorival
Starting Member

19 Posts

Posted - 2008-04-21 : 12:27:38
Excellent guys!
Thank you so much!
Go to Top of Page
   

- Advertisement -