Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Extract Data from Field?

Author  Topic 

ywb
Yak Posting Veteran

55 Posts

Posted - 2006-03-02 : 16:27:21
Hi,

I have my customer table currently in the following format

custID     custName     custAddress     city     state
1     CustomerABC     4 Main Road, Irvine, CA     Irvine     CA
2     CustomerDEF     123 Boundary Street, New York, NY     New York     NY
3     CustomerXYZ     8 25th Avenue, San Francisco, CA     San Francisco     CA

As you can see, both the info in fields "city" and "state" is repeated in the "custAddress" field. Now I would like to create a new column called "streetAddress" that would elimiate this repetition and simply store eg. "4 Main Road". How can I do this?



ywb.

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2006-03-02 : 16:45:09
I doubt all your data will be this cleanly formatted but this might get you most of the way there:

set nocount on

create table #customer
(custID int, custName varchar(15), custAddress varchar(40), city varchar(15), state varchar(2))
go
insert #customer
select 1, 'CustomerABC', '4 Main Road, Irvine, CA', 'Irvine', 'CA' union all
select 2, 'CustomerDEF', '123 Boundary Street, New York, NY', 'New York', 'NY' union all
select 3, 'CustomerXYZ', '8 25th Avenue, San Francisco, CA', 'San Francisco', 'CA'
go
alter table #customer add address1 varchar(30)
go

update #customer set
address1 = substring(replace(replace(custAddress, ', ' + city, ''), ', ' + state, ''),1,30)
from #customer

select custid
,custname
,address1
,city
,state
from #customer

drop table #customer

output:
custid custname address1 city state
----------- --------------- ------------------------------ --------------- -----
1 CustomerABC 4 Main Road Irvine CA
2 CustomerDEF 123 Boundary Street New York NY
3 CustomerXYZ 8 25th Avenue San Francisco CA


Be One with the Optimizer
TG
Go to Top of Page

ywb
Yak Posting Veteran

55 Posts

Posted - 2006-03-03 : 13:17:28
Thanks! That works!
Go to Top of Page
   

- Advertisement -