Вот что я нашел и протестировал:
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO
CREATE FUNCTION [dbo].[SplitStrings] ( @IDsList VARCHAR(MAX) )
RETURNS @IDsTable TABLE ( [ID] VARCHAR(MAX) )
AS
BEGIN
DECLARE @ID VARCHAR(MAX)
DECLARE @Pos VARCHAR(MAX)
SET @IDsList = LTRIM(RTRIM(@IDsList)) + ','
SET @Pos = CHARINDEX(',', @IDsList, 1)
IF REPLACE(@IDsList, ',', '') <> ''
BEGIN
WHILE @Pos > 0
BEGIN
SET @ID = LTRIM(RTRIM(LEFT(@IDsList, @Pos - 1)))
IF @ID <> ''
BEGIN
INSERT INTO @IDsTable
( [ID] )
VALUES ( CAST(@ID AS VARCHAR) )
END
SET @IDsList = RIGHT(@IDsList, LEN(@IDsList) - @Pos)
SET @Pos = CHARINDEX(',', @IDsList, 1)
END
END
RETURN
END
GO
Вот как вызывать функцию:
SELECT * FROM dbo.SplitStrings('123,548,198,547,965')