DELIMITER $$ CREATEPROCEDURE get_clients() BEGIN SELECT * FROM clients; END$$
DELIMITER ;
4 参数
1 2 3 4 5 6 7 8 9 10 11 12 13
DROPPROCEDUREIFEXISTS get_clients_by_state;
DELIMITER $$ CREATEPROCEDURE get_clients_by_state ( state CHAR(2) ) BEGIN SELECT * FROM clients c WHERE c.state = state; END$$
DELIMITER ;
调用:
1
CALL get_clients_by_state('CA')
4.1 带默认值的参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
DROPPROCEDUREIFEXISTS get_clients_by_state;
DELIMITER $$ CREATEPROCEDURE get_clients_by_state ( state CHAR(2) ) BEGIN IF state ISNULLTHEN---------- SET state = 'CA'; ---------- ENDIF; ---------- SELECT * FROM clients c WHERE c.state = state; END$$
DELIMITER ;
调用:
1
CALL get_clients_by_state(NULL)
IF-ELSE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
DROPPROCEDUREIFEXISTS get_clients_by_state;
DELIMITER $$ CREATEPROCEDURE get_clients_by_state ( state CHAR(2) ) BEGIN IF state ISNULLTHEN SELECT * FROM clients; ELSE SELECT * FROM clients c WHERE c.state = state; ENDIF; END$$
DELIMITER ;
更简洁的写法:
1 2 3 4 5 6 7 8 9 10 11 12 13
DROPPROCEDUREIFEXISTS get_clients_by_state;
DELIMITER $$ CREATEPROCEDURE get_clients_by_state ( state CHAR(2) ) BEGIN SELECT * FROM clients c WHERE c.state = IFNULL(state, c.state); END$$
DELIMITER $$ CREATEPROCEDURE get_unpaid_invoices_for_client( client_id INT, OUT invoices_count INT, -- ---------------- OUT invoices_total DECIMAL(9, 2) -- ---------------- ) BEGIN SELECTCOUNT(*), SUM(invoice_total) INTO invoices_count, invoices_total -- ---------------- FROM invoices i WHERE i.client_id = client_id AND payment_total = 0; END$$
DELIMITER ;
调用:
1 2 3 4 5
set @invoices_count = 0; set @invoices_total = 0; call sql_invoicing.get_unpaid_invoices_for_client (3, @invoices_count, @invoices_total); select @invoices_count, @invoices_total;
5 变量
1 2 3 4 5
-- User or session variables set @invoices_count = 0;