﻿IF OBJECT_ID('[fnConvertStringIntListToTable]') IS NOT NULL BEGIN
  DROP FUNCTION [fnConvertStringIntListToTable]
END  
GO

CREATE FUNCTION [fnConvertStringIntListToTable] (
    @pString NVARCHAR(4000),
    @pDelimiter NCHAR(1)
) RETURNS TABLE AS RETURN (
  WITH Split(stpos, endpos) AS (
    SELECT 0 AS stpos, CHARINDEX(@pDelimiter,@pString) AS endpos
    UNION ALL
    SELECT endpos + 1, CHARINDEX(@pDelimiter,@pString,endpos+1)
    FROM Split
    WHERE endpos > 0
  )
  SELECT 
     ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS Rn
    ,CAST(SUBSTRING(@pString, stpos, COALESCE(NULLIF(endpos, 0), LEN(@pString) + 1) - stpos) AS int) AS Data
  FROM Split
);
GO