MS 澳门新葡亰赌995577SQL 字符拆分存处理

澳门新葡亰赌995577 7

MS SQL Server没有split()函数,但是我们可以写一个Table-valued
Functions定义函数[dbo].[udf_SplitStringToTable] :
澳门新葡亰赌995577 1

澳门新葡亰赌995577 2澳门新葡亰赌995577 3

CREATE FUNCTION [dbo].[udf_SplitStringToTable] 
( 
    @string NVARCHAR(MAX), 
    @delimiter CHAR(1) 
) 
RETURNS @result TABLE([ID] INT IDENTITY(1,1),value NVARCHAR(MAX) 
) 
BEGIN 
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 
    BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1

        INSERT INTO @result (value) VALUES (SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)        
    END 
    RETURN 
END

Source Code

再写另外一个Scalar-valued
Function自定义函数[dbo].[udf_SplitString]:
澳门新葡亰赌995577 4

澳门新葡亰赌995577 5澳门新葡亰赌995577 6

CREATE FUNCTION [dbo].[udf_SplitString]
(
    @string NVARCHAR(MAX), 
    @delimiter CHAR(1),
    @index INT
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE @rtn NVARCHAR(MAX)
    SELECT @rtn = [value] FROM [dbo].[udf_SplitStringToTable] (@string,@delimiter) WHERE [ID] = @index
    RETURN @rtn
END
GO

Source Code

上面代码示例中@index参数即是你想获取第几个字符串,举个例子吧:
澳门新葡亰赌995577 7