您可以使用以下函数将列表转换为表格:
CREATE FUNCTION DelimitedStringToTable (@cdl varchar(8000), @delimiter varchar(1))
RETURNS @list table (
Token varchar(1000)
)
AS
BEGIN
DECLARE @token varchar(1000)
DECLARE @position int
SET @cdl = @cdl + @delimiter -- tack on delimiter to end
SET @position = CHARINDEX(@delimiter, @cdl, 1)
WHILE @position > 0
BEGIN
SET @token = LEFT(@cdl, @position - 1)
INSERT INTO @list (Token) VALUES (@token)
SET @cdl = RIGHT(@cdl, DATALENGTH(@cdl) - @position)
SET @position = CHARINDEX(@delimiter, @cdl, 1)
END
RETURN
END
然后你可以使用这样的东西来查找所有匹配项:
SELECT list1.*
FROM DelimitedStringToTable('1,2,3', ',') list1
INNER JOIN DelimitedStringToTable('2', ',') list2 ON list1.Token = list2.Token