2016-06-07 140 views
0

如何從字符串中提取值?我試圖分成3個新的列。城市,州和郵編的單獨列。SQL從字符串中提取值

我已經試過

select address2, 
left(address2, charindex('',address2)-1) 
from table 

和---當我嘗試下面的代碼,我得到「傳遞給左或子功能無效的長度參數」

,LTRIM(substring(a.Address2, CHARINDEX(' ', a.Address2)+1, CHARINDEX(' ', substring(a.address2, charindex(' ', 
a.address2)+1, len(a.address2)))-1)) 

我可以打出來這個城市(West Warwick除外)使用下面的代碼,但不知道如何使它適用於狀態和zip。這也消除了錯誤。

SUBSTRING(Address2,1,CHARINDEX(' ', a.address2+ ' ')-1) as city 

任何想法要嘗試什麼?

enter image description here

回答

2

它看起來像你的郵政編碼和您的國家都是一樣的長度。如果這是真的,你應該能夠使用這樣的事情:

SELECT 
    LEFT(a.Address2,LEN(a.Address2) - 13) AS City, 
    RIGHT(LEFT(a.Address2,LEN(a.Address2) - 11),2) AS State, 
    RIGHT(a.Address2,10) AS Zip_Code 
FROM 
    table; 

演示代碼

創建表和數據:

CREATE TABLE MyTable (Address2 VARCHAR(100)); 

INSERT INTO MyTable 
VALUES 
    ('SAN DIEGO CA 92128-1234'), 
    ('WEST WARWICK RI 02893-1349'), 
    ('RICHMOND IN 47374-9409'); 

查詢:

SELECT 
    LEFT(Address2,LEN(Address2) - 13) AS City, 
    RIGHT(LEFT(Address2,LEN(Address2) - 11),2) AS State, 
    RIGHT(Address2,10) AS Zip_Code 
FROM 
    MyTable; 

輸出:

enter image description here

+0

我必須有where子句嗎?我仍然收到「傳遞給LEFT或SUBSTRING函數的無效長度參數」。 – BIReportGuy

+0

我確實更新了'State'邏輯 - 我被關閉了一個。如果仍然出現錯誤,那就意味着有一些記錄'state'或'zip'(或兩者)的長度與您提供的示例數據中的長度不相同。 – Nicarus

+0

這似乎消除了錯誤,但我只知道如何使它適用於一列。 (West Warwick除外)SUBSTRING(Address2,1,CHARINDEX('',address2 +'')-1)作爲城市 – BIReportGuy

0

既然你只有3件(城市/州/郵編),你可以採取在SQL Server 2008及更高版本稱爲parsename功能的優勢。 (該功能的初衷是解析出對象名稱。)

使用replaceparsename函數的組合可以使您能夠將數據分成3部分,即使狀態長度(不太可能)或Zip(更可能)更改。

實施例的數據:

create table #my_table 
    (
     address2 varchar(75) not null 
    ) 

insert into #my_table values ('CONNERSVILLE IN 47331-3351') 
insert into #my_table values ('WEST WARWICK RI 02893-1349') 
insert into #my_table values ('RICHMOND IN 47374-9409') 
insert into #my_table values ('WILLIAMSBURG IN 47393-9617') 
insert into #my_table values ('FARMERSVILLE OH 45325-9226') 
--this record is an example of a likely scenario for when the zip length would change. 
insert into #my_table values ('WILLIAMSBURG IN 47393') 

解決方案:

with len_vals as 
    (
     select t.address2 
     , len(parsename(replace(t.address2,' ','.'), 1)) as zip_len 
     , len(parsename(replace(t.address2,' ','.'), 2)) as st_len 
     from #my_table as t 
     group by t.address2 
    ) 
select left(a.address2, len(a.address2) - b.zip_len - b.st_len - 2) as city 
, substring(a.address2, len(a.address2) - b.zip_len - 2, b.st_len) as st 
, right(a.address2, b.zip_len) as zip_code 
from #my_table as a 
inner join len_vals as b on a.address2 = b.address2 

結果:

exampleDataResults