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

user_sell_stocks.sql 961 B

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
  1. DELIMITER //
  2. CREATE PROCEDURE SellStock(IN user_id INT, IN stock_id INT, IN sell_quantity INT, IN stock_price DECIMAL(15,2))
  3. BEGIN
  4. DECLARE owned_quantity INT;
  5. -- Check if user owns enough stocks
  6. SELECT quantity INTO owned_quantity FROM user_stocks WHERE user_id = user_id AND stock_id = stock_id;
  7. IF owned_quantity < sell_quantity THEN
  8. SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Insufficient stock quantity';
  9. END IF;
  10. -- Remove the stocks from the user's portfolio
  11. UPDATE user_stocks SET quantity = quantity - sell_quantity WHERE user_id = user_id AND stock_id = stock_id;
  12. -- Add the funds to the user's balance
  13. UPDATE users SET available_funds = available_funds + (sell_quantity * stock_price) WHERE user_id = user_id;
  14. -- Record the transaction
  15. INSERT INTO transactions (user_id, stock_id, quantity, price_at_transaction)
  16. VALUES (user_id, stock_id, -sell_quantity, stock_price);
  17. END //
  18. DELIMITER ;
Tip!

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

Comments

Loading...