Monday, July 21, 2014

SQL Function fnSplitIn2Rows

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:        tCarter
-- Create date: 4/14/2014
-- Description:    
-- usage:
/*  1. (select * from fnSplitIn2Rows(@listItems,'','')

    2. IF @listItems IS NOT NULL
        BEGIN
        ....

        inner join table1 t1 with (nolock) on t2.id = t1.id
        inner join (select * from fnSplitIn2Rows(@listItems,'','')) UFNOUTPUT
                  on t1.id = UFNOUTPUT.itemvalue
        END
        ELSE
        BEGIN
        ....   
        inner join table1 t1 with (nolock) on t2.id = t1.id
        END

*/
-- =============================================
CREATE FUNCTION [dbo].[fSplitIn2Rows]
    (
      @PInStrSource varchar(8000) = NULL,
      @pInChrSeparator char(1) = '|'
    )
    RETURNS
        @ARRAY TABLE (ItemValue VARCHAR(1000))
AS
BEGIN
    DECLARE @CurrentStr varchar(2000)
    DECLARE @ItemStr varchar(200)
    
    SET @CurrentStr = @PInStrSource
    
    WHILE Datalength(@CurrentStr) > 0
    BEGIN
        IF CHARINDEX(@pInChrSeparator, @CurrentStr,1) > 0
            BEGIN
                   SET @ItemStr = SUBSTRING (@CurrentStr, 1, CHARINDEX(@pInChrSeparator, @CurrentStr,1) - 1)
                SET @CurrentStr = SUBSTRING (@CurrentStr, CHARINDEX(@pInChrSeparator, @CurrentStr,1) + 1, (Datalength(@CurrentStr) - CHARINDEX(@pInChrSeparator, @CurrentStr,1) + 1))
                INSERT @ARRAY (ItemValue) VALUES (ltrim(@ItemStr))
               END
         ELSE
             BEGIN                
                INSERT @ARRAY (ItemValue) VALUES (ltrim(@CurrentStr))
                   BREAK;
                END
    END
    RETURN
END

No comments:

Post a Comment