admin

SQL Server 2008-分隔地址字段

sql

我有一个地址栏,其中包含地址,州和邮政编码。我想将地址,郊区,州和邮政编码提取到单独的列中,由于地址的长度是可变的,如何用a分隔地址和“其他”详细信息,这怎么办呢?State的长度可以为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

阅读 236

收藏
2021-07-01

共1个答案

admin

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

请注意,您将需要用表名替换上面的子查询中我所谓的地址。

2021-07-01