Thursday, February 19, 2009

SQL - Last Index Of lastIndexOf

Quick flush - lastIndexOf in two varieties of SQL plus using the technique to cut off the last segment in a materialized path:

-- MySQL example of last index of, looking for the /
SELECT LENGTH("/HELLO/WORLD/STRINGS") - INSTR(REVERSE("/HELLO/WORLD/STRINGS"), "/") + 1;
13
-- T-SQL example of last index of, looking for the /
SELECT LEN('/HELLO/WORLD/STRINGS') - CHARINDEX('/', REVERSE('/HELLO/WORLD/STRINGS')) + 1;
13
-- MySQL example of cutting off the last segment of a path
SELECT SUBSTR("/A/B/C", 1, LENGTH("/A/B/C") - INSTR(REVERSE("/A/B/C"), "/"));
/A/B
-- T-SQL example of cutting off the last segment of a path
SELECT SUBSTRING('/A/B/C', 1, LEN('/A/B/C') - CHARINDEX('/', REVERSE('/A/B/C')));
/A/B
view raw gistfile1.sql hosted with ❤ by GitHub