views:

77

answers:

1

I want to always update the value of an update row in the database.

Imagine, i have a table with names and prices Every time a row is inserted or updated, i want to lower the price by a fixed amount.

How can I do this with SQL server 2005?

I have now something like

CREATE TRIGGER LowerPriceOnInsert ON products
AFTER INSERT, UPDATE
AS
    IF UPDATE(ProductPrice)
+3  A: 

Ok, so let's say you wanted to reduce the price by 5 cents:

UPDATE p
  SET price = price - 0.05
  FROM dbo.Products AS p
  INNER JOIN inserted AS i
  ON p.ProductID = i.ProductID;

http://msdn.microsoft.com/en-us/library/ms191300.aspx

Aaron Bertrand
+1, what I was thinking, good link too!
KM
It works, however, i cannot change the values of the rows anymore. I get an error saying that: The row value(s) updated or deleted either do not make the row unique or they alter multiple rows.While i just alter the price of one row using management studio. Any idea?Btw vote up for the answer anyway
Henri
I got it fixed by removing the IF UPDATE(ProductPrice). Thnx a lot!
Henri
Henri, it seems like you do not have a primary key on your table? Can you show the actual code and table structure in the question, or start a new question? Tough to debug commentary. :-)
Aaron Bertrand