以下存储过程仅接受显式写出实数的参数。例如:CALL test11(46)
。
我希望它重写,以便它可以接受类似于以下内容:
SELECT *, CALL test11(vendor_id) FROM vendors;
或者
CALL test11(SELECT vendor_id FROM vendors WHERE vendor_name = 'Micro Center');
我理解第一个/前一个是没有意义的,因为可以实现IF语句而不必求助于存储过程。但我发现后者非常重要。
存储过程语法:
DELIMITER //
CREATE PROCEDURE test11(IN vendor_id_var INT)
BEGIN
DECLARE sum_balance_due_var DECIMAL(9, 2);
SELECT SUM(invoice_total - payment_total - credit_total)
INTO sum_balance_due_var
FROM invoices i
JOIN vendors v ON v.vendor_id = i.vendor_id
WHERE i.vendor_id = vendor_id_var
GROUP BY i.vendor_id, vendor_name;
IF sum_balance_due_var > 0 THEN
SELECT CONCAT('Balance due: $', sum_balance_due_var) AS message;
ELSE
SELECT 'Balance paid in full' AS message;
END IF;
END//
DELIMITER ;
供应商表:
CREATE TABLE vendors (
vendor_id INT(11) NOT NULL AUTO_INCREMENT,
vendor_name VARCHAR(50) NOT NULL,
-- other columns
)
发票表:
CREATE TABLE invoices (
invoice_id INT(11) NOT NULL AUTO_INCREMENT,
vendor_id INT(11) NOT NULL,
invoice_total DECIMAL(9,2) NOT NULL,
payment_total DECIMAL(9,2) NOT NULL DEFAULT '0.00',
credit_total DECIMAL(9,2) NOT NULL DEFAULT '0.00',
-- other columns
)
一些示例数据:
INSERT INTO vendors (vendor_id, vendor_name) VALUES (34, 'IBM');
INSERT INTO vendors (vendor_id, vendor_name) VALUES (37, 'Blue Cross');
INSERT INTO invoices (invoice_id, vendor_id, invoice_total, payment_total, credit_total) VALUES (19, 34, 116.54, 116.54, 0.00);
INSERT INTO invoices (invoice_id, vendor_id, invoice_total, payment_total, credit_total) VALUES (52, 34,1083.58,1083.58, 0.00);
INSERT INTO invoices (invoice_id, vendor_id, invoice_total, payment_total, credit_total) VALUES (46, 37, 224.00, 224.00, 0.00);
INSERT INTO invoices (invoice_id, vendor_id, invoice_total, payment_total, credit_total) VALUES (50, 37, 116.00, 116.00, 0.00);
INSERT INTO invoices (invoice_id, vendor_id, invoice_total, payment_total, credit_total) VALUES (113, 37,224.00, 0.00, 0.00);
答案 0 :(得分:1)
将其定义为FUNCTION
:
CREATE FUNCTION test11(IN vendor_id_var INT)
RETURNS text -- or whatever type you want returned
BEGIN
-- your existing code
RETURN <something>
END
并删除单词CALL
:
SELECT *, test11(vendor_id)
FROM vendors
这是一个UDF,就像使用内置一样。