如何解析sql server 2012中的未知长度字符串

时间:2013-06-05 07:44:38

标签: sql-server parsing string-parsing

如何使用分隔符('。')将未知长度字符串解析为不同的列。

declare osversion varchar(100)
set osversion = '6.2.9295'
SELECT [Part1] = LEFT(osversion,CHARINDEX('.',osversion) - 1), 
   [Part2] = SUBSTRING(osversion,CHARINDEX('.',osversion) + 1, 
                       CHARINDEX('.',osversion,CHARINDEX('.',
                       osversion) + 1) - (CHARINDEX('.',osversion) + 1)), 
   [Part3] = SUBSTRING(osversion,CHARINDEX('.',
                       osversion,CHARINDEX('.',osversion) + 1) + 1,
                       DATALENGTH(osversion) - CHARINDEX('.',
                       osversion,CHARINDEX('.',osversion) + 1) - 
                       CHARINDEX('.',REVERSE(osversion))), 
       from table1

结果:

Part1   Part2   Part3   
6   2   9295

此结果适用于固定长度的字符串。我想解析一个未知长度的字符串。 比如'86 .52.929.695.22.1234'。请帮忙。

1 个答案:

答案 0 :(得分:0)

我的目的是在SQL中重新创建C#的string.Split函数。这是代码

CREATE FUNCTION [dbo].[f_Split](
@String NVARCHAR (4000), 
@Delimiter NVARCHAR (10)
)

RETURNS @T TABLE ([Value] NVARCHAR(4000))
BEGIN
    DECLARE @NEXTSTRING NVARCHAR(4000)
    DECLARE @POS INT,@DELIM_SIZE INT
    DECLARE @NEXTPOS INT
SELECT
    @NEXTSTRING = '',
    @String = @String + @Delimiter,
    @DELIM_SIZE = LEN(@Delimiter)

SET @POS = CHARINDEX(@Delimiter,@String)
SET @NEXTPOS = 1

WHILE (@POS <>  0)
BEGIN
    SET @NEXTSTRING = SUBSTRING(@String,1,@POS - 1)
    INSERT INTO @T ( [VALUE]) VALUES (@NEXTSTRING)
    SET @String = SUBSTRING(@String,@POS +@DELIM_SIZE,LEN(@String))
    SET @NEXTPOS = @POS
    SET @POS  = CHARINDEX(@Delimiter,@String)
END

 RETURN

END

您可以像这样调用函数

DECLARE @temp nvarchar(255); SELECT @temp = '86.52.929.695.22.1234'; 
SELECT * FROM dbo.f_Split(@temp,'.');

这是输出:

Value
86
52
929
695
22
1234