简体   繁体   中英

Changing the value of a table field after it has already been inserted

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?

To change one row:

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

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

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

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 |
+----+--------------------+----------+---------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM