Table Valued Functions
Split delimeter string to integer
USE [SampleDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[split_delimited_int]
(
@RecordIDList VARCHAR(MAX),
@Delimiter VARCHAR(10) = ','
)
RETURNS @ReturnValues TABLE (Number INT)
AS
BEGIN
DECLARE @RecordID VARCHAR(10)
DECLARE @Start INT = 0
DECLARE @Pos INT = 1
SET @RecordIDList = @RecordIDList + @Delimiter
SET @Pos = CHARINDEX(@Delimiter, @RecordIDList, 1)
WHILE @Pos > 0 BEGIN
SET @RecordID = LTRIM(RTRIM(SUBSTRING(@RecordIDList, @Start, @Pos - @Start)))
IF @RecordID <> ''
INSERT INTO @ReturnValues (Number) VALUES (CAST(@RecordID AS Int))
SET @Start = @Pos + len(@Delimiter)
SET @Pos = CHARINDEX(@Delimiter, @RecordIDList, @Start)
END
RETURN
ENDExample usage
Output
Split single delimeter string to table
A table-valued function that splits a string into rows of substrings, based on a specified separator character.
Example usage
Output
STRING_SPLIT (Transact-SQL)
If you are using SQL Server 2016 and later, you can use the built-in function STRING_SPLIT.
The preceding STRING_SPLIT usage is a replacement for a common anti-pattern. Such an anti-pattern can involve the creation of a dynamic SQL string in the application layer or in Transact-SQL. Or an anti-pattern can be achieved by using the LIKE operator. See the following example SELECT statement:
Last updated
Was this helpful?