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

8 comments:

  1. awesome. btw your gists still don't show up in the feed.

    ReplyDelete
  2. I'm loving the gists because 1) it looks good and 2) blogger doesn't foobar my code when saving a post -- but I'm not sure if I can get the gists to render content that will be picked up by feed readers as it is inserted with a script tag. I'm going to look in to this and I have some ideas on how it might be done...

    ReplyDelete
  3. Oh, and 3) the gist is stored in version control and you can go back and edit it.

    ReplyDelete
  4. Thank you! Just what I was looking for.

    - Juha S

    ReplyDelete
  5. thank you for the solution
    Devrim K

    ReplyDelete