Last active
November 7, 2017 23:36
-
-
Save vestel/6b1d465315a8856b57f0626229d439d7 to your computer and use it in GitHub Desktop.
MySQL specific adventure about table creation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- RUN ONLY ONCE TO DEPLOY PROCEDURE & FUNCTION INTO DB | |
DELIMITER $$ | |
-- FUNCTION TAKES STRING, DELIMITER AND POSITION | |
-- AND RETURNS SUBSTRING OF DEFINED POSITION BY DELIMITERS | |
-- IF DELIMITER NOT FOUND OR OUT OF RANGE WILL RETURN '' (empty string) | |
-- Example: SPLIT_STR('ABRA / SCHWABRA / KADABRA',' / ',3) returns 'KADABRA' | |
-- | |
-- IF DELIMITER NOT FOUND OR OUT OF RANGE WILL RETURN '' (empty string) | |
-- Example: SPLIT_STR('-/-',',',1) returns '' | |
-- EXample: SPLIT_STR('1,2,3',',',5) returns '' | |
CREATE FUNCTION SPLIT_STR(x VARCHAR(65432), delim VARCHAR(5), pos INT) | |
RETURNS VARCHAR(65432) DETERMINISTIC | |
BEGIN | |
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos), | |
LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1), | |
delim, ''); | |
END$$ | |
-- PROCEDURE TAKES str STRING AND SPLITS IT BY delim INTO TEMP TABLE | |
-- whie saving value converts it to INT | |
CREATE PROCEDURE FILT3R(str VARCHAR(65432), delim VARCHAR(5)) | |
BEGIN | |
SET @x = 1; | |
DROP TEMPORARY TABLE IF EXISTS filt3r; | |
CREATE TEMPORARY TABLE filt3r(id int) ENGINE=Memory; | |
REPEAT | |
SET @id = (SELECT CAST(SPLIT_STR(str,delim,@x) AS UNSIGNED)); | |
INSERT INTO filt3r SET id=@id; | |
SET @x = @x + 1; | |
UNTIL SPLIT_STR(str,delim,@x) = '' END REPEAT; | |
END$$ | |
DELIMITER ; | |
-- RUN ONCE ENDS HERE | |
-- USAGE | |
CALL FILT3R('1,2,3,5,6',','); -- this will populate temporary table filt3r with values | |
SELECT id FROM filt3r WHERE id not in ( <INSERT_YOUR_QUERY_HERE> ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment