Link to home
Start Free TrialLog in
Avatar of erikTsomik
erikTsomikFlag for United States of America

asked on

Writing a SQL query to consolidate 2 fileds into the same format

I have a table users which consists 2 column phoneNumber and Contact (there more columns into that table userID).

PhoneNUmber is an old Field (in the diffferent format xxx-xxx-xxxx,xxx.xxx.xxxx,(xxx)xxx-xxxx).Wjhat I want to do is to take that field and format it into this format (xxx-xxx-xxxx) and put it into the column Contact
Avatar of Tapan Pattanaik
Tapan Pattanaik
Flag of India image

Hi erikTsomik,

If you want to retrieve "xxx-xxx-xxxx" from   "xxx-xxx-xxxx,xxx.xxx.xxxx,(xxx)xxx-xxxx)" you can use the below query.

select left(phoneNumber,12) from users ;
Avatar of erikTsomik

ASKER

But that will give a mixture of numbers .What I need to is to take the phoneNumber  column and update to format xxx-xxx-xxxx and put it into the Contact column
can you share more data with us !!!!!!
Avatar of Scott Pletcher
You'll just end up with different formats again!

Strip the formatting from the stored data.  Formatting chars are not actual data in this case.

Add a formatting code, if you need it, to determine how to format the data when it is output/displayed.

C'mon, wouldn't format: xxxxxxxxxx be a lot simpler and more consistent all the way around!?
How would I strip it off can you give me an example
You could use a function that stripped every nonnumeric char.

Or, if your data is reasonably clean, just embed REPLACEs:

UPDATE dbo.tablename
SET contact = REPLACE(REPLACE(REPLACE(REPLACE(phone_number, '-', ''), '.', ''), '(', ''), ')') --...
WHERE
    contact IS NULL OR contact = ''


Then add a CHECK to the table to prevent bad data from getting in:

ALTER TABLE table_name
ADD CONSTRAINT table_name__CK_contact CHECK(contact NOT LIKE '%[^0-9]%')
will constraint remove strip off unwanted data
No, it will prevent non-numeric char(s) from being INSERTed into the contact column.
For example:


create table table_name ( contact varchar(30) not null )

ALTER TABLE table_name
 ADD CONSTRAINT table_name__CK_contact CHECK(contact NOT LIKE '%[^0-9]%')
 go
 
 insert into table_name values('111')
 insert into table_name values('12345678990898098')
 insert into table_name values('1234b')
 go
 select * from table_name


If you wanted, you could also add a check to verify that the length is either 7 or 10 digits.
ASKER CERTIFIED SOLUTION
Avatar of awking00
awking00
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial