将地址转换为两列

时间:2015-02-27 02:07:01

标签: sql sql-server-2012

我在iad_Line1 = 415 W 10th St S列中有一个地址,想要将415拆分为列ad_housenumber,将'W 10th St S'拆分为列iad_street

这可以在SQL中作为多行的批量更新吗?

3 个答案:

答案 0 :(得分:0)

检查

DECLARE @ADDRESS AS NVARCHAR(50)

SET @ADDRESS = '415 W 10th St S'

SELECT 
    SUBSTRING(@ADDRESS, 0, charindex(' ',@address) ) as ad_housenumber ,
    RTRIM(SUBSTRING(@ADDRESS, charindex(' ',@address)+1,LEN(@ADDRESS) - 3)) AS iad_street

使用更新声明更新了答案:

declare @source table(iad_Line1 varchar(50), ad_housenumber varchar(50), iad_street varchar(50))

insert into @source values('415 W 10th St S',null,null)

update @source
set ad_housenumber = SUBSTRING(iad_Line1, 0, charindex(' ',iad_Line1) ) 
,iad_street = RTRIM(SUBSTRING(iad_Line1, charindex(' ',iad_Line1)+1,LEN(iad_Line1) - 3))
from
@source

select * from @source

答案 1 :(得分:0)

试试这个,

DECLARE @t TABLE
  (
     AlphaColumn VARCHAR(30),
     DOORNO      INT,
     ADDRESS1    VARCHAR(30)
  )

INSERT INTO @t
            (AlphaColumn)
VALUES      ('415 W 10th St S'),
            ('34 St S'),
            ('415 h St SAVC'),
            ('123 d'),
            ('ww 1')

SELECT *
FROM   @t

UPDATE Y
SET    DOORNO = ( CASE
                    WHEN AlphaStart > 0 THEN LEFT(AlphaColumn, AlphaStart - 1)
                    ELSE AlphaColumn
                  END ),
       ADDRESS1 = ( CASE
                      WHEN noStart > 0 THEN RIGHT(AlphaColumn, LEN(AlphaColumn) + 1 - AlphaStart)
                      ELSE AlphaColumn
                    END )
FROM   (SELECT patindex('%[a-z]%', AlphaColumn) AS [AlphaStart],
               patindex('%[0-9]%', AlphaColumn) AS [noStart],
               AlphaColumn,
               DOORNO,
               ADDRESS1
        FROM   @t)y
WHERE  [AlphaStart] <> 1

SELECT *
FROM   @t 

答案 2 :(得分:-1)

这是你在寻找什么?

DECLARE @ADDRESS AS NVARCHAR(50)

SET @ADDRESS = '415 W 10th St S'

SELECT SUBSTRING(@ADDRESS, 1,1) + '-'+ SUBSTRING(@ADDRESS, 2,2) AS ADD1, 
       RTRIM(SUBSTRING(@ADDRESS, 4,LEN(@ADDRESS) - 3)) AS ADD2