# [web] Simple T-SQL Trigger

## Recommended Posts

plywood    103
Making a simple website for my game and using MS SQL Server 2000. I would like to create a simple trigger between two fields on a table so that when the value of one field changes, the other field is automatically updated. This would only be an update trigger. The code example below is not the exact scenario I'm facing, and may be a poor example, but the solution to it will answer the real (more complex) problem I am facing. Here is my pseudocode:
CREATE TRIGGER tr_monsters_hp_update
ON monsters m
FOR UPDATE
AS
IF m.monster_life changed from 1.0 to 0.0 /* From Alive to Dead */
BEGIN
UPDATE monsters m SET m.monster_hp = 0 /* ...then set hit points to 0 */
END


I only want the trigger to fire when the [monsters].[monster_life] field is updated from a value of 1.0 to a value of 0.0. In such a case, I want [monsters].[monster_hp] to be set to 0. My problem is coming up with the correct code: (1)to determine whether the updated meets the required criteria (monster_life changing from 1.0 to 0.0), and (2) making sure the update only fires for the record whose monster_life meets that criteria. This is my first SQL trigger and I have read a few guides and am aware of the built-in INSERTED and DELETED tables, but the examples I've found really aren't answering my question. Any ideas? Best, ply

##### Share on other sites
ID Merlin    119
UPDATE monsters m SET m.monster_hp = 0 WHERE m.monster_id = INSERTED.monster_id /* ...then set hit points to 0 */

The code you've written will update them all...