在SQL中分隔地址字符串

时间:2013-06-25 20:53:15

标签: sql sql-server string

我在sql server数据库上有一个名为Houses的表,其中包含一个包含(丹麦语)地址的列。在丹麦,街道名称总是在门牌号码之前,然后是公寓信息,如果它是公寓。我想将街道名称和数字分成两个字符串并忽略公寓信息。我的数据如下:

Address
Fisker Vejen 48B, 1.TV
Baunevej 29

因此,一些街道名称有超过1个单词,有些地址有公寓信息,有些则没有。一些门牌号也有非数字字符。我希望它是:

Street_Name      House_Number
Fisker Vejen     48B
Baunevej         29

我可以使用以下代码提取街道名称:

select case when a.NumStart> 0 then LEFT(a.Address,a.NumStart-1) ELSE a.Address END as Street_Name,
    FROM
    (select patindex('%[0-9]%',Address) as [NumStart], Address from Houses) a

但是如果没有楼层信息,我无法获得门牌号码。有人可以帮忙吗?

谢谢!

3 个答案:

答案 0 :(得分:4)

这是一个解决方案:

SELECT *
        ,LEFT(Address,PATINDEX('% [0-9]%',Address)-1)'Street'
        , SUBSTRING(Address,PATINDEX('% [0-9]%',Address)+1,PATINDEX('%[0-9],%',Address+ ',')-PATINDEX('% [0-9]%',Address))'House Number'
FROM T

演示:SQL Fiddle

更新:如果门牌号始终以数字开头,后面跟逗号或者什么都没有,那么这将有效:

SELECT *
        ,LEFT(Address,PATINDEX('% [0-9]%',Address)-1)'Street'
        , SUBSTRING(Address,PATINDEX('% [0-9]%',Address)+1,PATINDEX('%, %',Address+ ', ')-PATINDEX('% [0-9]%',Address)-1)'House Number'
FROM Table1

演示2:SQL Fiddle2

答案 1 :(得分:1)

SELECT 
  Vejnavn, 
  case when NumEnd > 0 then left(rest,NumEnd-1) else rest end Housenumber 
FROM ( 
  SELECT 
    *, 
    patindex('%[^0-9A-Z]%',rest) numend 
  FROM (
    SELECT 
      CASE WHEN a.NumStart> 0 THEN LEFT(a.Adresse,a.NumStart-1) ELSE a.Adresse END as Vejnavn,
      CASE WHEN a.NumStart> 0 THEN SUBSTRING(a.Adresse,a.NumStart,100) ELSE '' END rest
    FROM (
      SELECT 
        PATINDEX('%[0-9]%',Adresse) AS [NumStart], 
        Adresse 
      FROM Houses
    ) a
   ) b 
 ) c 

sqlfiddle

答案 2 :(得分:0)

尝试这样的事情:

SELECT
  CASE WHEN  a.NumStart> 0 then LEFT(a.Adresse, a.NumStart-1) ELSE a.Adresse END as Vejnavn,
  Substring(a.adress, a.Numstart, a.Comma - a.Numstart + 1) as HouseNumber
FROM (
  SELECT 
    PATINDEX('%[0-9]%', Adress) as [NumStart], 
    CHARINDEX(',', Adress + ',') as Comma,
    Adresse, 
    Salgsdato 
  FROM Houses) a