Skip to content

Commit a9988c6

Browse files
committed
SQL script to update BLSample.subLocation via a cursor to remove duplicate rows
1 parent 134b111 commit a9988c6

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
-- Use a curson to hold the result set from a complex SELECT query to get the
2+
-- blSampleIds of rows that duplicate the combination of (containerId, location, subLocation).
3+
-- Then get the rows one by one and run an UPDATE statement against each row in
4+
-- an effort to make the combination of (containerId, location, subLocation) unique.
5+
6+
DELIMITER //
7+
8+
BEGIN NOT ATOMIC
9+
10+
DECLARE done INT DEFAULT FALSE;
11+
DECLARE ids, jpath TEXT;
12+
DECLARE i, id INT;
13+
DECLARE cur CURSOR FOR
14+
SELECT q.blSampleIds
15+
FROM (
16+
SELECT containerId, location, subLocation, count(*) cnt, JSON_ARRAYAGG(blSampleId) blSampleIds
17+
FROM BLSample
18+
WHERE location IS NOT NULL
19+
GROUP BY containerId, location, subLocation
20+
HAVING cnt > 1
21+
ORDER BY containerId, location, subLocation
22+
) q;
23+
24+
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
25+
26+
OPEN cur;
27+
28+
read_loop: LOOP
29+
FETCH cur INTO ids;
30+
IF done THEN
31+
LEAVE read_loop;
32+
END IF;
33+
34+
FOR i IN 0..JSON_LENGTH(ids)-1
35+
DO
36+
37+
SET jpath := CONCAT('$[', i, ']');
38+
SET id := CAST(JSON_EXTRACT(ids, jpath) AS INT);
39+
40+
UPDATE BLSample SET subLocation = i+1 WHERE blSampleId = id; -- AND subLocation IS NULL;
41+
42+
END FOR;
43+
44+
END LOOP;
45+
46+
CLOSE cur;
47+
END; //
48+
49+
DELIMITER ;

0 commit comments

Comments
 (0)