Skip to Main Content
  • Questions
  • Above quiz ask during interview.-Particular string converted into table of column

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Abhijit.

Asked: January 18, 2017 - 5:05 am UTC

Last updated: January 18, 2017 - 6:32 am UTC

Version: 12c

Viewed 1000+ times

You Asked

Interviewer ask if You give a input string like ,
Input-1
'abhi,abhang,London,'ora,pvt,ltd''
Input-2
'salman,khan,Mumbai,'Boston,pvt,ltd''
required output is,
OutputTable is
-----------------------------------------------------
fname | lname | city | Address
-----------------------------------------------------
abhi abhang London ora,pvt,ltd
----------------------------------------------------
salman khan Mumbai Boston,pvt,ltd
----------------------------------------------------

and Connor said...

A lot depends on how rigorous and variable the data really is, but this should get you started

SQL> create table t as
  2  select 'abhi,abhang,London,''ora,pvt,ltd''' tag from dual
  3  union all
  4  select 'salman,khan,Mumbai,''Boston,pvt,ltd''' tag from dual;

Table created.

SQL>
SQL> with comma_pos as
  2  (
  3  select
  4    tag,
  5    instr(tag,',',1,1) i1,
  6    instr(tag,',',1,2) i2,
  7    instr(tag,',',1,3) i3
  8  from t
  9  )
 10  select
 11    substr(tag,1,i1-1) fname,
 12    substr(tag,i1+1,i2-i1-1) lname,
 13    substr(tag,i2+1,i3-i2-1) city,
 14    trim('''' from substr(tag,i3+1)) address
 15  from  comma_pos;

FNAME                               LNAME                               CITY                             ADDRESS
----------------------------------- ----------------------------------- ----------------------------------- -----------------
abhi                                abhang                              London                           ora,pvt,ltd
salman                              khan                                Mumbai                           Boston,pvt,ltd

2 rows selected.


If *any* of the data could be within quotes, then you need to do something more sophisticated like keeping track of whether you are "in" a quote or "out" of one.

There's an example of something similar to that here

https://asktom.oracle.com/pls/asktom/f?p=100:11:::::P11_QUESTION_ID:11471734233362


Is this answer out of date? If it is, please let us know via a Comment