SQL从字符串

时间:2016-06-07 21:41:24

标签: sql sql-server tsql

如何从字符串中提取值?我正在尝试分成3个新列。城市,州和邮政编码的单独列。

我试过

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除外),但不确定如何使其适用于state和zip。这也消除了错误。

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

任何想法尝试什么?

enter image description here

2 个答案:

答案 0 :(得分: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;

DEMO CODE

创建表格和数据:

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

答案 1 :(得分: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