0

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

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'。请帮忙。

4

1 回答 1

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
于 2013-06-05T08:37:43.980 回答