如何从T-SQL中的字符串中提取地址号

时间:2018-10-29 09:11:13

标签: sql-server

我在sql列中有地址,其中也包含可能的门号,地址和邮政编码,即以下格式

120 westminister way Road, London (NW10 5NQ)
5 westminister way Road, London (NW10 5NQ)

我需要在两列中分别提取门号和地址。我尝试使用PATINDEX'%[0-9]%',但我无法确定整数LEN

select 
  PostCode = iif(charindex('(',[address]) > 1, REVERSE(SUBSTRING(REVERSE([address]),2, CHARINDEX('(', REVERSE([address]))-2)),'')
  ,PATINDEX('%[0-9]%', [address]) DoorNoIndex
  ,SUBSTRING([address],PATINDEX('%[0-9]%', [address]), 2) DoorNo
  ,LEN( PATINDEX('%[0-9]%', [address])) doorNoLength

预期输出

i) door no 120
2) door no 5

5 个答案:

答案 0 :(得分:2)

尝试一下

DECLARE @Temp AS TABLE (ID INT IDENTITY,Data nvarchar(100))
INSERT INTO @Temp
SELECT '120 westminister way Road, London (NW10 5NQ)' UNION ALL
SELECT '5 westminister way Road, London (NW10 5NQ)'

;WITH CTE
AS
(
SELECT  ID,
        Split.a.value('.','nvarchar(1000)') AS Data,
        ROW_NUMBER()OVER(PARTITION BY ID ORDER BY ID) AS rnk
FROM(
        SELECT ID,CAST('<S>'+REPLACE(Data,' ','</S><S>')+'</S>' AS XML) Data
         FROM @Temp
    )dt 
    CROSS APPLY Data.nodes('S') AS Split(a)
)
SELECT ID, 'Door No: '+CAST(Data AS VARCHAR(10))  AS [Output expected]
FROM CTE WHERE rnk=1

结果

ID  Output expected
------------------
1   Door No: 120
2   Door No: 5

答案 1 :(得分:2)

门号似乎总是在字符串的开头,所以您可以简单地

DECLARE @Temp AS TABLE (ID INT IDENTITY,Data nvarchar(100))
INSERT INTO @Temp
SELECT N'120 westminister way Road, London (NW10 5NQ)' UNION ALL
SELECT N'5 westminister way Road, London (NW10 5NQ)';

SELECT ID,
       'Door No: ' + LEFT(Data, PATINDEX('%[a-z]%', Data) -2) DoorNumber
FROM @Temp;

SELECT ID,
       'Door No: ' + LEFT(Data, CHARINDEX(' ', Data) -1) DoorNumber
FROM @Temp;

返回:

+----+--------------+
| ID |  DoorNumber  |
+----+--------------+
|  1 | Door No: 120 |
|  2 | Door No: 5   |
+----+--------------+

答案 2 :(得分:2)

您可以如下所示尝试查询。

create table #temp (id int identity(1,1), DoorNo Varchar(50))
insert into #temp (DoorNo) select * from (
select 'Door No:' + substring('120 westminister way Road, London (NW10 5NQ)',1,PATINDEX('% %','120 westminister way Road, London (NW10 5NQ)')) as doorno
UNION ALL
select 'Door No:' + substring('5 westminister way Road, London (NW10 5NQ)',1,PATINDEX('% %','5 westminister way Road, London (NW10 5NQ)')) as doorno
)a

select * from #temp
drop table #temp

输出将如下所示

id  DoorNo
1   Door No:120 
2   Door No:5 

希望这对您有帮助。

答案 3 :(得分:0)

寻找不是数字​​的第一个字符:

SELECT CONCAT('Door No: ', PATINDEX('%[^0-9]%', address))
FROM yourtable

答案 4 :(得分:0)

DocumentRoot