Wednesday, August 1, 2012

Return nth index of a delimited string in TSQL

CREATE FUNCTION [dbo].[fn_SplitSelect] (@sep VARCHAR(32), @s VARCHAR(MAX), @index INT)

RETURNS NVARCHAR(MAX)
AS
    BEGIN
        DECLARE @xml XML
        SET @XML = N'' + REPLACE(@s, @sep, '') + ''
        
        DECLARE @ret NVARCHAR(MAX)

        SELECT @ret = Item
        FROM (
                    SELECT r.value('.','VARCHAR(5)') as Item, ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS rownum
                    FROM @xml.nodes('//root/r') AS RECORDS(r)
                    ) t
             WHERE t.rownum = @index
        

        RETURN @ret
    END



No comments:

Post a Comment