第二篇 重要函数应用3

进一步改造目标2: 可自定义连接符,而不局限只能是逗号(“,”)。

引用金蝶K3的行转列函数,功能更强,可以不限逗号;

/******************************************************************************

 * Function Name: fn_SplitStringToTable                                                                                      

 * Description:  拆分一个字符串       *

 * Parameters:    @InputString –要拆分的字符串                                *

 *                @Delimeter – 自定义的连接符                                      *

 ******************************************************************************/

ALTER  FUNCTION fn_SplitStringToTable

(

    @InputString VARCHAR(8000),

    @Delimeter   CHAR(1)

)

RETURNS @Table TABLE

(

    FSequence INT IDENTITY(1, 1),

    FValue    VARCHAR(511),

    FPosition INT,

    FLength   INT

)

BEGIN

    DECLARE @Position INT

    

    SELECT @Position = 1

    

    IF RIGHT(@InputString, LEN(@Delimeter)) <> @Delimeter

        SET @InputString = @InputString + @Delimeter

    

    WHILE SUBSTRING(@InputString, @Position, 1) = CHAR(10) OR

          SUBSTRING(@InputString, @Position, 1) = CHAR(13)

    BEGIN

        SELECT @Position = @Position + 1

    END

    

    WHILE @Position <= CHARINDEX(@Delimeter, @InputString, @Position)

    BEGIN

        INSERT INTO @Table(FValue, FPosition, FLength)

             VALUES (RTRIM(LTRIM(SUBSTRING(@InputString,

                                           @Position,

                                           CHARINDEX(@Delimeter,

                                                     @InputString,

                                                     @Position) - @Position))), @Position, CHARINDEX(@Delimeter, @InputString, @Position) - @Position)

        SELECT @Position = CHARINDEX(@Delimeter, @InputString, @Position) + 1

        

        WHILE SUBSTRING(@InputString, @Position, 1) = CHAR(10) OR

              SUBSTRING(@InputString, @Position, 1) = CHAR(13)

        BEGIN

            SELECT @Position = @Position + 1

        END

    END

    RETURN

END

GO

--测试

select * FROM dbo.fn_SplitStringToTable('SSSSSS,ASDF-ASDFASDF','-')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值