SQL Query将地址分成多个列

时间:2016-10-12 21:20:02

标签: sql sql-server

在SQL Server中,我将地址数据存储在单个列中,如下所示:

123 Fake St #25

我想将这些数据分为3列,如下所示:

Number   Street     Apt
-----------------------
123      Fake St    #25

我想我可以使用修剪和搜索功能的组合,但我不确定。我很感激帮助。

2 个答案:

答案 0 :(得分:2)

唯一的提示是从开始的第一个空白和从结束的第一个空白。但是 - 当然! - 会有地址没有满足这种模式...

然而,有些事情要开始:

DECLARE @addr VARCHAR(100)='123 Fake St #25';

WITH Blanks AS
(
    SELECT @addr AS Addr
          ,CHARINDEX(' ',@addr) AS FirstBlank
          ,CHARINDEX(' ',REVERSE(@addr)) AS LastBlankFromBack
)
SELECT LTRIM(RTRIM(LEFT(Addr,FirstBlank-1))) AS Number
      ,LTRIM(RTRIM(SUBSTRING(Addr,FirstBlank+1,LEN(Addr)-FirstBlank-LastBlankFromBack+1))) AS Street
      ,LTRIM(RTRIM(RIGHT(Addr,LastBlankFromBack-1))) AS Apt 
FROM Blanks 

答案 1 :(得分:0)

假设地址将具有与您的示例类似的模式,您可以尝试以下操作。如前所述,如果分隔符未知,则无法获得准确的解决方案。

创建一个函数来返回标量值,如此

        CREATE FUNCTION [dbo].[SplitGet] (
            @test AS VARCHAR(255)
            ,@field AS VARCHAR(1)
            )
        RETURNS VARCHAR(255)
        AS
        BEGIN
            DECLARE @ReturnValue VARCHAR(255) = '';
            DECLARE @Alpha VARCHAR(255) = '';
            DECLARE @Beta VARCHAR(255) = '';
            DECLARE @Gamma VARCHAR(255) = '';
            DECLARE @ind INT = 1;  
            WHILE (@ind < LEN(@test))
            BEGIN
                IF (ISNUMERIC(substring(@test, @ind, 1)) = 1)
                BEGIN
                    SET @Alpha = @Alpha + cast(substring(@test, @ind, 1) AS NVARCHAR(1));
                    SET @ind = @ind + 1;
                END
                ELSE
                BEGIN
                    BREAK;
                END
            END

            SET @Beta = Substring(Substring(@test, @ind, len(@test)), 0, charindex('#', Substring(@test, @ind, len(@test)), 0))
            SET @Gamma = RTRIM(substring(@test, charindex('#', @test, 0), len(@test)));

            IF (@field = 'n') --Numnber
            BEGIN
                SET @ReturnValue = @Alpha;
            END
            ELSE IF (@field = 'a') --Address
            BEGIN
                SET @ReturnValue = @Beta;
            END
            ELSE
            BEGIN --Apartment
                SET @ReturnValue = @gamma;
            END

            RETURN RTRIM(@ReturnValue)
        END

一样使用它
DECLARE @test varchar(255) = '123 Fake st #25'
SELECT dbo.[SplitGet](@test,'n'),dbo.[SplitGet](@test,'a'),dbo.[SplitGet](@test,'')