Skip to content

Instantly share code, notes, and snippets.

@mdnmdn
Last active August 23, 2018 12:03
Show Gist options
  • Save mdnmdn/1a57e28092353f21f03bceed1a39432a to your computer and use it in GitHub Desktop.
Save mdnmdn/1a57e28092353f21f03bceed1a39432a to your computer and use it in GitHub Desktop.
TSQL SplitInts, SplitStrings: string to list of string and to list of ints
CREATE FUNCTION SplitInts
(
@list varchar(8000),
@delimiter char(1) = '#'
)
RETURNS TABLE WITH SCHEMABINDING
AS
RETURN (
SELECT [value] from (
SELECT [value] = cast(y.i.value('(./text())[1]', 'varchar(8000)') as int)
FROM (SELECT x = CONVERT(XML, '<i>'
+ REPLACE(@list, @delimiter, '</i><i>')
+ '</i>').query('.')) AS a
CROSS APPLY x.nodes('i') AS y (i)
) v where coalesce(@list,'') != ''
)
GO;
-- select * from utils.SplitInts ('11,44,77,99', ',')
CREATE FUNCTION SplitStrings
(
@list varchar(8000),
@delimiter char(1) = '#'
)
RETURNS TABLE WITH SCHEMABINDING
AS
RETURN (
SELECT [value] from (
SELECT [value] = coalesce(y.i.value('(./text())[1]', 'varchar(8000)'),'')
FROM (SELECT x = CONVERT(XML, '<i>'
+ REPLACE(@list, @delimiter, '</i><i>')
+ '</i>').query('.')) AS a
CROSS APPLY x.nodes('i') AS y (i)
) v where @list is not null
)
GO;
-- select * from utils.SplitStrings ('hi#red#blue#greee', '#')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment