用新行分隔TEXT块

时间:2012-03-30 14:23:13

标签: sql sql-server tsql triggers sql-server-2000

在T-SQL中,我需要用新行字符分隔TEXT值,然后在每一行循环。

换句话说,我需要一个explode()函数,但是对于T-SQL,我需要循环每一行。

我很难创建一个新的临时表,并将此表中的字符串行存储为行,然后使用游标循环。我只是不确定如何分隔字符串。

在T-SQL中有快速的方法吗?

1 个答案:

答案 0 :(得分:3)

(我猜你的数据会超过4000个字符。)

分割功能:

CREATE FUNCTION dbo.Split
(
    @RowData nvarchar(2000),
    @SplitOn nvarchar(5)
)  
RETURNS @RtnValue table 
(
    Id int identity(1,1),
    Data nvarchar(2000)
) 
AS  
BEGIN 
    Declare @Cnt int
    Set @Cnt = 1

    While (Charindex(@SplitOn,@RowData)>0)
    Begin
        Insert Into @RtnValue (data)
        Select 
            Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

        Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
        Set @Cnt = @Cnt + 1
    End

    Insert Into @RtnValue (data)
    Select Data = ltrim(rtrim(@RowData))

    Return
END

爆炸功能:

CREATE FUNCTION dbo.*tableName*_Explode
(
    @id int
) 
RETURNS @RtnValue table 
(
    Id int,
    Data NVARCHAR(2000)
)
AS
BEGIN
    DECLARE @LINEBREAK AS varchar(2)
    SET @LINEBREAK = CHAR(13) + CHAR(10)

    DECLARE @short_text NVARCHAR(2000)
    DECLARE @short_text_length INT

    DECLARE @sub_length INT
    SET @sub_length = 2000
    DECLARE @sub_index INT
    SET @sub_index = 1


BEGIN
    SET @short_text = (select SUBSTRING(*tableData*,@sub_index,@sub_length) from *tableName* WHERE id = @id)
    SET @short_text_length = DATALENGTH(@short_text)

            WHILE (@short_text_length > 0)
    BEGIN
        Insert Into @RtnValue (id,data)
        SELECT @id, @short_text

        SET @sub_index = (@sub_index + @sub_length)
        SET @short_text = (select SUBSTRING(*tableData*,@sub_index,@sub_length) from *tableName* WHERE id = @id)
        SET @short_text_length = DATALENGTH(@short_text)
    END

    IF (SELECT COUNT(*) FROM @RtnValue) = 0
        Insert Into @RtnValue (id,data)
        SELECT @id, ''
    END

    RETURN
END