-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathW2_stored_procedures.sql
56 lines (42 loc) · 1.49 KB
/
W2_stored_procedures.sql
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
---> list all procedures
SHOW PROCEDURES;
SELECT * FROM TASTY_BYTES_CLONE.RAW_POS.ORDER_HEADER
LIMIT 100;
---> see the latest and earliest order timestamps so we can determine what we want to delete
SELECT MAX(ORDER_TS), MIN(ORDER_TS) FROM TASTY_BYTES_CLONE.RAW_POS.ORDER_HEADER;
---> save the max timestamp
SET max_ts = (SELECT MAX(ORDER_TS) FROM TASTY_BYTES_CLONE.RAW_POS.ORDER_HEADER);
SELECT $max_ts;
SELECT DATEADD('DAY',-180,$max_ts);
---> determine the necessary cutoff to go back 180 days
SET cutoff_ts = (SELECT DATEADD('DAY',-180,$max_ts));
---> note how you can use the cutoff_ts variable in the WHERE clause
SELECT MAX(ORDER_TS) FROM TASTY_BYTES_CLONE.RAW_POS.ORDER_HEADER
WHERE ORDER_TS < $cutoff_ts;
USE DATABASE TASTY_BYTES;
---> create your procedure
CREATE OR REPLACE PROCEDURE delete_old()
RETURNS BOOLEAN
LANGUAGE SQL
AS
$$
DECLARE
max_ts TIMESTAMP;
cutoff_ts TIMESTAMP;
BEGIN
max_ts := (SELECT MAX(ORDER_TS) FROM TASTY_BYTES_CLONE.RAW_POS.ORDER_HEADER);
cutoff_ts := (SELECT DATEADD('DAY',-180,:max_ts));
DELETE FROM TASTY_BYTES_CLONE.RAW_POS.ORDER_HEADER
WHERE ORDER_TS < :cutoff_ts;
END;
$$
;
SHOW PROCEDURES;
---> see information about your procedure
DESCRIBE PROCEDURE delete_old();
---> run your procedure
CALL DELETE_OLD();
---> confirm that that made a difference
SELECT MIN(ORDER_TS) FROM TASTY_BYTES_CLONE.RAW_POS.ORDER_HEADER;
---> it did! We deleted everything from before the cutoff timestamp
SELECT $cutoff_ts;