-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.sql
More file actions
58 lines (51 loc) · 1.54 KB
/
schema.sql
File metadata and controls
58 lines (51 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
DROP DATABASE IF EXISTS product_db;
CREATE DATABASE product_db;
USE product_db;
-- Product table
CREATE TABLE products (
product_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10,2) CHECK (price >= 0),
quantity INT DEFAULT 0 CHECK (quantity >= 0)
);
-- Category table for join
CREATE TABLE categories (
category_id INT AUTO_INCREMENT PRIMARY KEY,
category_name VARCHAR(100) NOT NULL
);
-- Add category_id to products (FK for join)
ALTER TABLE products
ADD category_id INT,
ADD FOREIGN KEY (category_id) REFERENCES categories(category_id);
-- Insert some categories
INSERT INTO categories (category_name) VALUES ('Electronics'), ('Books'), ('Groceries');
-- Log table
CREATE TABLE product_update_log (
log_id INT AUTO_INCREMENT PRIMARY KEY,
product_id INT,
old_price DECIMAL(10,2),
new_price DECIMAL(10,2),
old_quantity INT,
new_quantity INT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Stored Procedure
DELIMITER //
CREATE PROCEDURE ApplyDiscount(IN discount_percent DECIMAL(5,2))
BEGIN
UPDATE products
SET price = price - (price * (discount_percent / 100));
END //
DELIMITER ;
-- Trigger for logs
DELIMITER //
CREATE TRIGGER after_product_update
AFTER UPDATE ON products
FOR EACH ROW
BEGIN
IF OLD.price != NEW.price OR OLD.quantity != NEW.quantity THEN
INSERT INTO product_update_log (product_id, old_price, new_price, old_quantity, new_quantity)
VALUES (OLD.product_id, OLD.price, NEW.price, OLD.quantity, NEW.quantity);
END IF;
END //
DELIMITER ;