SPLIT() Function
--Creates an 'InLine' Table Valued Function (TVF)
CREATE FUNCTION dbo.Split
( @Delimiter varchar(5),
@List varchar(8000)
)
RETURNS @TableOfValues table
( RowID smallint IDENTITY(1,1),
[Value] varchar(50)
)
AS
BEGIN
DECLARE @LenString int
WHILE len( @List ) > 0
BEGIN
SELECT @LenString =
(CASE charindex( @Delimiter, @List )
WHEN 0 THEN len( @List )
ELSE ( charindex( @Delimiter, @List ) -1 )
END
)
INSERT INTO @TableOfValues
SELECT substring( @List, 1, @LenString )
SELECT @List =
(CASE ( len( @List ) - @LenString )
WHEN 0 THEN ''
ELSE right( @List, len( @List ) - @LenString - 1 )
END
)
END
RETURN
END
Usage Examples:
-- 1.)
SELECT *
FROM dbo.Split( ',', '11,23,3,14' ) AS s
ORDER BY cast( s.[Value] AS int )
-- 2.)
SELECT *
FROM dbo.Split( '', 'BobJaneMaryLiHsiaoLubor' ) AS s
ORDER BY s.[Value]
-- 3.)
DECLARE @MyList varchar(50)
SET @MyList = ( '2,4,7,8' )
SELECT
m.RowID,
m.LastName,
m.FirstName
FROM #MyTable AS m
JOIN dbo.Split( ',', @MyList ) AS l
ON m.RowID = cast( l.[Value] AS int )
ORDER BY
m.LastName,
m.FirstName
No comments:
Post a Comment