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
 Help on trigger

Author  Topic 

Ciupaz
Posting Yak Master

232 Posts

Posted - 2011-09-21 : 02:53:18
Hi all,
I have a table "Products" like this one:

ProductID - Price - OtherColumn

with some values


23 - 34.99
24 - 15.90
12 - 120.00
5 - 34.00
32 - 35.90
.....


How can I write a trigger that updates automatically this table when someone or something make an Insert or Update to set the Price field = 0 when its value is negative, and this *only* for ProductID = 32?

Thanks in advance.

Luigi



visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-09-21 : 05:43:22
[code]
CREATE TRIGGER UpdatePrice
ON Products
FOR INSERT,UPDATE
AS
BEGIN
UPDATE t
SET t.Price=0
FROM Products t
INNER JOIN INSERTED i
ON i.ProductID = t.ProductID
AND i.ProductID =32
WHERE i.Price < 0
END
[/code]

I would have done this by means of check constraint though to avoid this insert/update first off all.

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

Ciupaz
Posting Yak Master

232 Posts

Posted - 2011-09-21 : 08:03:39
Perfect, thank you Visakh.

Luigi
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-09-21 : 08:47:27
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -