I recently had a friend ask for help comparing two comma seperated lists in SQL server using a UDF. I started based around the Split UDF I wrote, and continued from there. The simplest and most performant thing I could think of was to use an INNER JOIN to compare the table values of the two lists. Then just compare the counts you get back to make sure they're all the same. Here's the UDF:
SET
ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE
FUNCTION IsCommaListMatch
(
@list1 varchar(255),
@list2 varchar(255)
)
RETURNS bit
AS
BEGIN
DECLARE @isMatch bit
DECLARE @list1Values TABLE (val int)
DECLARE @list2Values TABLE (val int)
INSERT INTO @list1Values SELECT * FROM dbo.Split(@list1)
INSERT INTO @list2Values SELECT * FROM dbo.Split(@list2)
DECLARE @count1 int
DECLARE @count2 int
DECLARE @count1Join int
DECLARE @count2Join int
SELECT @count1=COUNT(val) FROM @list1Values
SELECT @count2=COUNT(val) FROM @list2Values
SELECT
@count1Join=COUNT(list1Values.val),
@count2Join=COUNT(list2Values.val)
FROM
@list1Values list1Values
INNER JOIN @list2Values list2Values
ON
list1Values.val=list2Values.val
IF @count1=@count2 AND @count1=@count1Join AND @count2=@count2Join
SET @isMatch=1
ELSE
SET @isMatch=0
RETURN @isMatch
END
GO
As always, feel free to contact me if you have ideas on improving this.