forked from yan12125/test_yan
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect_text.sql
More file actions
30 lines (26 loc) · 1.24 KB
/
select_text.sql
File metadata and controls
30 lines (26 loc) · 1.24 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
DELIMITER //
-- Use procedures instead of functions becuase of the need to return multiple values
DROP PROCEDURE IF EXISTS select_text; //
CREATE PROCEDURE select_text(IN title_ VARCHAR(256), INOUT index_ INTEGER, OUT text_ VARCHAR(65536))
BEGIN
-- "Exceptions" in mysql
-- http://www.devshed.com/c/a/MySQL/Using-the-SIGNAL-Statement-for-Error-Handling/
DECLARE index_out_of_range CONDITION FOR SQLSTATE '99001';
DECLARE title_not_found CONDITION FOR SQLSTATE '99002';
DECLARE lineCount INTEGER;
DECLARE result VARCHAR(65536);
SET lineCount = (SELECT `lines` FROM texts WHERE title = title_);
IF lineCount IS NULL THEN
SIGNAL title_not_found SET MESSAGE_TEXT = "Title not found";
END IF;
IF (index_ = -1) THEN
-- RAND() is guaranteed to be in [0.0, 1.0)
SET index_ = FLOOR(RAND() * lineCount);
ELSEIF (index_ >= lineCount OR index_ < -1) THEN
SIGNAL index_out_of_range SET MESSAGE_TEXT = "Index out of range";
END IF;
SET result = NULL;
-- Use SUBSTRING_INDEX to split strings, which might be slow
-- http://stackoverflow.com/questions/9814430
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(`text`, "\n", index_ + 1), "\n", -1) INTO text_ FROM texts WHERE title = title_;
END//