tags:

views:

37

answers:

3

I am working with a CMS system, and using a kind of smartform am inserting fields into a table.

In these fields are the name of a product, quantity and cost.

cost and product name are taken from a products table, while quantity is input manually.

I understand this is not the best architecture, but I am limited with the system I am working with.

What I want to do, is change the value of cost after it is inserted, to quantity * cost.

What is the easiest way to do this?

A: 

You can run an UPDATE after the insert, using the identity field of the new product:

UPDATE products
SET cost = cost * quantity
WHERE product_id = @productId
Oded
+1  A: 

To change one row:

update  TheTable
set     cost = quantity * cost
where   pk = 123

If you run this multiple times, costs will explode ;-)

Andomar
+1 nice warning :)
sarnold
A: 

If you have your hands tied so tightly that you are unable to change the table structure, then you probably won't be able to use a trigger, but here goes anyway.

This is a sample table structure:

DROP TABLE IF EXISTS `products`;

CREATE TABLE `products` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `product` VARCHAR(255),
    `quantity` INT(11) NOT NULL,
    `cost` DECIMAL(6,2) NOT NULL,
    PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

Create a trigger which updates the cost prior to it being inserted into the products table:

DELIMITER //
DROP TRIGGER IF EXISTS update_cost//
CREATE TRIGGER update_cost BEFORE INSERT ON products
FOR EACH ROW BEGIN
    SET NEW.cost = NEW.cost * NEW.quantity;
END;
//
DELIMITER ;

Insert a couple of products into the table:

INSERT INTO `products` (`product`, `quantity`, `cost`) VALUES
('Acme portable hole', 10, 20),
('Acme jet pack', 1000, 2);

The cost is updated automatically:

SELECT * FROM prodcuts;

+----+--------------------+----------+---------+
| id | product            | quantity | cost    |
+----+--------------------+----------+---------+
|  1 | Acme portable hole |       10 |  200.00 |
|  2 | Acme jet pack      |     1000 | 2000.00 |
+----+--------------------+----------+---------+
Mike
I can change the table structure, just not the queries used to access it, but I can use a trigger. Thankyou.
Jacob
@Jacob: That's good news I suppose :-) I'm glad to have been able to help. At least a trigger should help to prevent costs exploding, as it will only occur once - when the row is inserted. It also means that you don't have to worry about doing this throughout your code.
Mike