Google
Information Storage and Retrieval: Separate the words (SQL Puzzle 15)

Pages

Friday, July 25, 2008

Separate the words (SQL Puzzle 15)

Problem: Given any sentence, break it into separate words. (The words are separated by spaces).

Solution:
select doc.EXTRACT('/l/text()').getstringVal()
from
(select 'I am a bad man' given from dual ) T ,
TABLE(xmlSequence(EXTRACT(XMLTYPE(''REPLACE(T.given,' ','')''),'/doc/l'))) doc

('I am a bad man' is an example)

1 comment:

Anonymous said...

This can also be achieved using
SELECT TRIM(',' FROM SUBSTR('I AM A BAD MAN'||' ',NVL(LAG(R.T) OVER (ORDER BY R.T),0)+1,R.T-NVL(LAG(R.T) OVER (ORDER BY R.T),0))) DONE
FROM
(SELECT INSTR('I AM A BAD MAN'||' ',' ',1,ROWNUM) T FROM ALL_OBJECTS)R
WHERE R.T<>0

Kartik