-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvariables_functions.sql
More file actions
55 lines (43 loc) · 1.11 KB
/
variables_functions.sql
File metadata and controls
55 lines (43 loc) · 1.11 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
-- Session Variables
SET @invoice_total = 0;
-- Local variables
DELIMITER $$
CREATE PROCEDURE get_risk_factor()
BEGIN
DECLARE risk_factor DECIMAL(9,2) DEFAULT 0;
DECLARE invoices_total DECIMAL(9,2);
DECLARE invoices_count INT;
SELECT count(*), sum(invoice_total)
INTO invoices_count, invoices_total
FROM invoices;
SET risk_factor = invoices_total/invoices_count * 5;
SELECT risk_factor;
END$$
DELIMITER ;
call sql_invoicing.get_risk_factor();
-- Functions
DELIMITER $$
CREATE FUNCTION get_risk_factor_for_client
(
client_id INT
)
RETURNS INT
READS SQL DATA
BEGIN
DECLARE risk_factor DECIMAL(9,2) DEFAULT 0;
DECLARE invoices_total DECIMAL(9,2);
DECLARE invoices_count INT;
SELECT count(*), sum(invoice_total)
INTO invoices_count, invoices_total
FROM invoices i
WHERE i.client_id = client_id;
SET risk_factor = invoices_total/invoices_count * 5;
RETURN IFNULL(risk_factor,0);
END$$
DELIMITER ;
DROP FUNCTION IF EXISTS get_risk_factor_for_client;
SELECT
client_id,
name,
get_risk_factor_for_client(client_id) as risk_factor
FROM clients;