SQL Server 2008 - 分隔地址字段

时间:2012-01-13 01:28:59

标签: sql sql-server-2008

我有一个包含地址,状态和邮政编码的地址列。我想将地址,郊区,州和邮政编码提取到单独的列中,如何做到这一点作为地址的长度是可变的,有一个^来分隔地址和“其他”细节。状态长度可以是2或3个字符,邮政编码总是4个字符。

PostalAddress                            TO BE  Address   Suburb       State  Postcode
28 Smith Avenue^MOOROOLBARK VIC 3138^    28 Smith Avenue  MOOROOLBARK  VIC    3138
16 Farr Street^HEYFIELD VIC 3858^        16 Farr Street   HEYFIELD     VIC    3858
17 Terry Road^LOWER PLENTY VIC 3093^     17 Terry Road    LOWER PLENTY VIC    3093  

2 个答案:

答案 0 :(得分:5)

SQL中的字符串解析很混乱,而且往往很脆弱。我通常认为最好在SQL之外完成这些任务。也就是说,鉴于上面的迷你规范,可以将数据解析为您想要的字段:

select 
  left(PostalAddress, charindex('^', PostalAddress) - 1) as street_address,
  left(second_part, len(second_part) - charindex(' ', reverse(second_part))) as suburb,
  right(second_part, charindex(' ', reverse(second_part))) as state,
  reverse(substring(reverse(PostalAddress), 2, 4)) as postal_code
from (
  select
    PostalAddress,
    rtrim(reverse(substring(reverse(PostalAddress), 6, len(PostalAddress) - charindex('^', PostalAddress) - 5))) as second_part
  from Addresses
) as t1

请注意,您需要将您的表名替换为我在上面的子查询中称为地址的内容。

您可以针对示例数据here查看此操作。

答案 1 :(得分:0)

在我的情况下,只是将字符串中的五位数作为邮政编码:

以下是我的代码:

Select SUBSTRING([Column or string],patindex('%[0-9][0-9][0-9][0-9][0-9]%',[Column or string]),5) AS 'Postcode'