使用T-SQL解析具有不同长度(字符/分号分隔)的字符串的函数

时间:2014-11-20 03:31:57

标签: sql sql-server function parsing stored-procedures

我有以下2个字符串

351856040520298,241111;1G,141007024755,A,1437.2453N,12100.2887E,3.10,206,0.8,21010000;
2G,141007024755,10,43.6,14.08,00.18,273295019.6;

和这一个

351856040520298,241111;1R,141117003059,A,1420.4629N,12058.7028E,0.0,77,0.9,20000006;2R,
141117003059,11,98.3,12.58,04.10,282098820.9

只是想正确解析它。我使用存储过程来解析它,但如果长度发生变化则无法解析。我需要一些帮助来开发一个功能,但我是新功能。

我需要解析或拆分它并使用函数或存储过程将其插入表中。

我试图在这里学习这个功能,但如果没有像我的字符串那样的正确样本,就无法理解它,例如,需要帮助。感谢所有帮助

Parse a comma-delimited string

2 个答案:

答案 0 :(得分:1)

-- Method 1 : split string based only on semi colon and not comma
CREATE FUNCTION [dbo].[ufn_SSVToTable] ( @StringInput VARCHAR(max) )
RETURNS @OutputTable TABLE ( [String] VARCHAR(max) )
AS
BEGIN

    DECLARE @String    VARCHAR(max)

    WHILE LEN(@StringInput) > 0
    BEGIN
        SET @String      = LEFT(@StringInput, 
                                ISNULL(NULLIF(CHARINDEX(';', @StringInput) - 1, -1),
                                LEN(@StringInput)))
        SET @StringInput = SUBSTRING(@StringInput,
                                     ISNULL(NULLIF(CHARINDEX(';', @StringInput), 0),
                                     LEN(@StringInput)) + 1, LEN(@StringInput))

        INSERT INTO @OutputTable ( [String] )
        VALUES ( @String )
    END

    RETURN
END

Go

declare @str1 varchar(max)
set @str1  = '351856040520298,241111;1G,141007024755,A,1437.2453N,12100.2887E,3.10,206,0.8,
              21010000;2G,141007024755,10,43.6,14.08,00.18,273295019.6;'

select String as [Method1] from [dbo].[ufn_SSVToTable] ( @str1 ) 

Go

---- Method 2 : split string based on both semi colon and comma

CREATE FUNCTION [dbo].[ufn_CSVToTable] ( @StringInput VARCHAR(max) )
RETURNS @OutputTable TABLE ( [String] VARCHAR(max) )
AS
BEGIN

    DECLARE @String    VARCHAR(max)

    WHILE LEN(@StringInput) > 0
    BEGIN
        SET @String      = LEFT(@StringInput, 
                                ISNULL(NULLIF(CHARINDEX(',', @StringInput) - 1, -1),
                                LEN(@StringInput)))
        SET @StringInput = SUBSTRING(@StringInput,
                                     ISNULL(NULLIF(CHARINDEX(',', @StringInput), 0),
                                     LEN(@StringInput)) + 1, LEN(@StringInput))

        INSERT INTO @OutputTable ( [String] )
        VALUES ( @String )
    END

    RETURN
END

Go

declare @str2 varchar(max)
set @str2  = '351856040520298,241111;1G,141007024755,A,1437.2453N,12100.2887E,3.10,206,0.8,
              21010000;2G,141007024755,10,43.6,14.08,00.18,273295019.6;'

select String as [Method2] from [dbo].[ufn_CSVToTable] ( replace(@str2,';',',')) 

Go

DEMO

答案 1 :(得分:0)

如果你在网上搜索了大量的t-sql分割功能的例子 - 这是我之前使用的一个...

http://www.codeproject.com/Tips/666620/T-SQL-Most-Practical-Split-Function