-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctions.sql
More file actions
75 lines (58 loc) · 2.1 KB
/
Functions.sql
File metadata and controls
75 lines (58 loc) · 2.1 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
-- Function to calculate revenue for a given period.
CREATE OR REPLACE FUNCTION library.fn_revenue_by_period (p_date_started DATE, p_date_finished DATE)
RETURNS NUMERIC AS $$
DECLARE
total_revenue NUMERIC;
BEGIN
SELECT SUM(quantity * price) INTO total_revenue
FROM library.tb07_ordered_item AS oi
JOIN library.tb06_order AS o ON o.id_order = oi.id_order
WHERE o.order_data BETWEEN p_date_started AND p_date_finished;
IF total_revenue IS NULL THEN
RETURN 0.0;
END IF;
RETURN total_revenue;
END;
$$ LANGUAGE plpgsql;
SELECT library.fn_revenue_by_period('2025-10-01', '2025-11-30');
-- Function to check books by author
CREATE OR REPLACE FUNCTION library.fn_get_books_by_author (p_author_name TEXT)
RETURNS TEXT AS $$
DECLARE book_count INT;
BEGIN
SELECT COUNT(*) INTO book_count
FROM library.tb02_author AS a
JOIN library.tb04_book AS b on b.id_author = b.id_author
WHERE a.author_name = p_author_name;
IF p_author_name IS NULL THEN
RETURN 'Error: invalid values';
END IF;
RETURN book_count;
END;
$$ LANGUAGE plpgsql;
SELECT library.fn_get_books_by_author ('Machado de Assis');
--Função de calcular o estoque atual real disponível
CREATE OR REPLACE FUNCTION library.fn_calculate_available_stock (p_book_id INT)
RETURNS INT AS $$
DECLARE total_stock INT;
stock_in_transit INT;
available_stock INT;
BEGIN
--Obtem o estoque atual do livro
SELECT quantity INTO total_stock
FROM library.tb04_book AS b
WHERE b.id_book = p_book_id;
--Se o livro não existir, gera uma exceção
IF p_book_id IS NULL THEN
RAISE EXCEPTION 'Book with ID % not found.', p_book_id;
END IF;
--Calcula a quantidade de livros atualmente indisponíveis 1 = Emprestado e 4 = Reservado
SELECT COALESCE(SUM(oi.quantity),0) INTO stock_in_transit
FROM library.tb07_ordered_item as oi
JOIN library.tb06_order as o on o.id_order = oi.id_order
WHERE oi.id_book = p_book_id AND o.id_order_status IN (1,4);
available_stock := total_stock - stock_in_transit;
RETURN available_stock;
END;
$$ LANGUAGE plpgsql;
SELECT library.fn_calculate_available_stock ('1');