[英]Create a Stored Procedure Debug
使用本網站的數據和模式:使用本網站的數據: https://www.sqlservertutorial.net/sql-server-sample-database/
我得到提示:
創建一個名為 placeOrder() 的存儲過程,調用它可以在數據庫中插入新訂單。 它將接收作為 INT 的 customerId、作為 INT 的 productId 和作為 INT 的 qty,並返回(作為輸出參數)表 orders 中創建的新行的 order_id。
此存儲過程將查找具有該特定產品最大庫存的商店並將該商店分配給訂單。 order_status 應設置為 1(即 Pending),當前系統日期(參見 function CURDATE)將分配給 order_date,required_date 列將從當前系統日期起 7 天(參見 function ADDDATE),並將分配 staff_id 列適用於在所選商店工作的任何人(根據之前的要求)。 由於 order_id 列不是自動遞增的列,因此您需要計算它的值。 您可以使用 max(order_id) 找出表中最高的 order_id。
order_item 行應設置為傳遞給存儲過程的 productId 和 qty。 item_id 應設置為 1(因為此訂單只有一件商品)。應使用傳遞的 productId 從產品表中檢索標價。 折扣值應設置為0
如果我對提示的理解正確,我需要首先找到具有最多特定產品的商店 ID。 擁有該商店后,我需要在“訂單”表中插入一行新數據,其中基本數據為 order_id、customer_id、order_status、order_date、required、date 和 staff_id。 我不明白問題的最后一部分在問什么/如何解決 go。
這是我當前的代碼,但我幾乎可以肯定它充滿了錯誤和注釋以及遺漏的部分,所以請盡可能幫助我:
DELIMITER //
CREATE procedure placeOrder (IN customerID INT, IN productID INT, IN QTY INT, OUT order_id INT)
BEGIN
DECLARE customerID INT;
DECLARE produtcID INT;
DECLARE quantity INT;
SELECT customer_id INTO customerID from customers where customer_id = customerID;
SELECT product_id INTO productID from order_items where product_id = productID;
SELECT quantity INTO qty from order_items where quantity = qty;
/**find store id with max stocks of product**/
select st.store_name, sk.store_id from stocks as sk
INNER JOIN
stores as st
ON sk.store_id = st.store_id
WHERE max(sk.quantity)
GROUP by sk.product_id;
select st.store_id from stores as st
INNER JOIN orders as o
ON st.store_id= o.store_id
Insert into orders (order_id, customer_id, order_status, order_date, required_date, staff_id)
WHERE order_status = '1',
AND order_date = select(curdate()),
AND required_date = adddate('order_date' +7),
AND staff_id = /**ANYONE from store listed in precious query (how do I relate these two queries)**
END
SELECT
查詢來設置已在參數中設置的變量。ORDER BY sk.quantity DESC LIMIT 1
INTO <variable>
來設置查詢中的變量。 如果不這樣做,查詢的結果將變成過程的結果,這在此處是不希望的。INSERT
語句中使用WHERE
。 WHERE
用於查找與條件匹配的現有行,而INSERT
用於創建新行。 您使用VALUES()
列出應分配給指定列的所有值。CREATE procedure placeOrder (IN customerID INT, IN productID INT, IN QTY INT, OUT orderId INT)
BEGIN
DECLARE topStoreId INT;
DECLARE staffId INT;
/**find store id with max stocks of product**/
select sk.store_id
from stocks as sk
INNER JOIN stores as st
ON sk.store_id = st.store_id
WHERE sk.product_id = productID
ORDER BY sk.quantity DESC
LIMIT 1
INTO topStoreId;
/* Pick an arbitrary staff from the selected store */
SELECT staff_id
FROM staffs
WHERE store_id = topStoreId
LIMIT 1
INTO staffId;
SELECT MAX(order_id)
FROM orders AS o
INTO orderId;
Insert into orders (order_id, customer_id, order_status, order_date, required_date, staff_id, store_id)
VALUES (orderId, customerId, 1, CURDATE(), DATE_ADD(CURDATE(), INTERVAL 1 WEEK), staffId, topStoreId);
END
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.