Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

purchase_stock_db.sql 1.2 KB

You have to be logged in to leave a comment. Sign In
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
  1. DELIMITER //
  2. CREATE PROCEDURE BuyStock(IN user_id INT, IN stock_id INT, IN buy_quantity INT, IN stock_price DECIMAL(15,2))
  3. BEGIN
  4. DECLARE funds DECIMAL(15,2);
  5. DECLARE total_cost DECIMAL(15,2);
  6. -- Calculate total cost of purchase
  7. SET total_cost = buy_quantity * stock_price;
  8. -- Check if user has enough funds
  9. SELECT available_funds INTO funds FROM users WHERE user_id = user_id;
  10. IF funds < total_cost THEN
  11. SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Insufficient funds';
  12. END IF;
  13. -- Deduct the total cost from the user's funds
  14. UPDATE users SET available_funds = available_funds - total_cost WHERE user_id = user_id;
  15. -- Add the stocks to the user's portfolio
  16. INSERT INTO user_stocks (user_id, stock_id, quantity, average_price)
  17. VALUES (user_id, stock_id, buy_quantity, stock_price)
  18. ON DUPLICATE KEY UPDATE
  19. quantity = quantity + buy_quantity,
  20. average_price = (average_price * quantity + stock_price * buy_quantity) / (quantity + buy_quantity);
  21. -- Record the transaction
  22. INSERT INTO transactions (user_id, stock_id, quantity, price_at_transaction)
  23. VALUES (user_id, stock_id, buy_quantity, stock_price);
  24. END //
  25. DELIMITER ;
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...