I have to create a function in sql which will validate a comma separated string.
example: string will be like @str = \'AB,CD,EF,GH\'
I have
This function will take your comma separated list and return a table, just like STRING_SPLIT()
which I think is only available for SQL Server 2016. Then, you'll just INNER JOIN
to the table based on your conditions. I usually set a table variable to the results of this function so I can reuse it.
ALTER FUNCTION [dbo].[ufn_split_string]
(
@RowData NVARCHAR(MAX),
@Delimeter NVARCHAR(MAX)
)
RETURNS @RtnValue TABLE
(
ID INT IDENTITY(1,1),
DataRow NVARCHAR(MAX)
)
AS
BEGIN
DECLARE @Iterator INT
SET @Iterator = 1
DECLARE @FoundIndex INT
SET @FoundIndex = CHARINDEX(@Delimeter,@RowData)
WHILE (@FoundIndex>0)
BEGIN
INSERT INTO @RtnValue (DataRow)
SELECT
Data = LTRIM(RTRIM(SUBSTRING(@RowData, 1, @FoundIndex - 1)))
SET @RowData = SUBSTRING(@RowData,
@FoundIndex + 1,
LEN(@RowData))
SET @Iterator = @Iterator + 1
SET @FoundIndex = CHARINDEX(@Delimeter, @RowData)
END
INSERT INTO @RtnValue (DataRow)
SELECT Data = LTRIM(RTRIM(@RowData))
RETURN
END
GO