3

The original format:

123-456-7890 

My goal format:

(123)456-7890

I wanted to go the route of concatenating between substrings but I continually get flagged for errors. I am unsure of a better method to go about implementing a way to format.

My query:

select || '(' || substr(telephone,0, 3)|| ')' || 
substr(telephone,4, 3)|| ' '|| 
substr(telephone,7, 4)) as telephone,
from book;

My current error:

"missing expression"

4 Answers4

0

You have an extra dangling parenthesis at the end of your SELECT, and you also have a dangling concatenation operator || in the front. Try this:

SELECT '(' || SUBSTR(telephone, 0, 3) || ')' ||
    SUBSTR(telephone, 4, 3) || ' ' || SUBSTR(telephone, 7, 4) AS telephone
FROM book

Update:

You should really use this query, because it turns out you also had a problem with forming your desired output as well:

SELECT '(' || SUBSTR(telephone, 1, 3) || ')' || SUBSTR(telephone, 5, 8) AS telephone
FROM book
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Using SUBSTR:

SQL> WITH sample_data AS(
  2  SELECT '123-456-7890' num FROM dual
  3  )
  4  -- end of sample_data mimicking real table
  5  SELECT num,
  6    '('
  7    || SUBSTR(num, 1, 3)
  8    ||
  9    ')'
 10    || SUBSTR(num, 5, 8) AS my_num
 11  FROM sample_data;

NUM          MY_NUM
------------ ---------------
123-456-7890 (123)456-7890

SQL>

Remember, the index for SUBSTR starts from 1. It is bad practice to use 0 as starting index.

You could also do it using REGEXP_REPLACE.

Pattern: (\d{3})(-)(\d{3})(-)(\d{4})

Expression: regexp_replace(num, '(\d{3})(-)(\d{3})(-)(\d{4})', '(\1)\3\4\5')

For example,

SQL> WITH sample_data AS(
  2  SELECT '123-456-7890' num FROM dual
  3  )
  4  -- end of sample_data mimicking real table
  5  SELECT num,
  6    regexp_replace(num, '(\d{3})(-)(\d{3})(-)(\d{4})', '(\1)\3\4\5') my_num
  7  FROM sample_data;

NUM          MY_NUM
------------ ---------------
123-456-7890 (123)456-7890

SQL>
Lalit Kumar B
  • 47,486
  • 13
  • 97
  • 124
0

You can use regular expressions to do.

select regexp_replace
(phoneNo,
  '([[:digit:]]{3})\-([[:digit:]]{3})\-([[:digit:]]{4})',
  '(\1)\2-\3'
) 
from(
select '123-456-7890' as phoneNo from dual)

Output

(123)456-7890
Utsav
  • 7,914
  • 2
  • 17
  • 38
0
SELECT '123-456-7890','('||SUBSTR('123-456-7890',1,3)||')'||SUBSTR('123-456-7890',5,8) FROM dual;
Prashant Mishra
  • 619
  • 9
  • 25