您要么必须将 F.LegalIssue 标准化为多行,要么必须使用 LIKE
就像是
CAST(E.ID A VARCHAR(50)) = F.LegalIssue
OR F.LegalIssue LIKE CAST(E.ID A VARCHAR(50)) + ',%'
OR '%,' + F.LegalIssue LIKE CAST(E.ID A VARCHAR(50)) + ',%'
OR '%,' + F.LegalIssue LIKE CAST(E.ID A VARCHAR(50))
如您所见,表的实际设计是问题所在。您应该避免使用您当前拥有的设计,并选择一个1 to many
或many to many
设计。
这是一个演示如何使用递归 CTE 展平值
创建测试表和数据
CREATE TABLE Tada(
ID INT,
SomeCommaString VARCHAR(50)
)
INSERT INTO Tada Values (1, '10'),(2,'5,6,12,16')
把桌子弄平
;WITH Vals AS (
SELECT
ID,
CASE
WHEN CHARINDEX(',',SomeCommaString) = 0
THEN SomeCommaString
WHEN CHARINDEX(',',SomeCommaString) > 0
THEN LEFT(SomeCommaString,CHARINDEX(',',SomeCommaString) - 1)
END Val,
CASE
WHEN CHARINDEX(',',SomeCommaString) > 0
THEN RIGHT(SomeCommaString,LEN(SomeCommaString) - CHARINDEX(',',SomeCommaString))
ELSE NULL
END Remainder
FROM Tada
UNION ALL
SELECT
ID,
CASE
WHEN CHARINDEX(',',Remainder) = 0
THEN Remainder
WHEN CHARINDEX(',',Remainder) > 0
THEN LEFT(Remainder,CHARINDEX(',',Remainder) - 1)
END Val,
CASE
WHEN CHARINDEX(',',Remainder) > 0
THEN RIGHT(Remainder,LEN(Remainder) - CHARINDEX(',',Remainder))
ELSE NULL
END Remainder
FROM Vals
WHERE Remainder IS NOT NULL
)
SELECT ID, Val
FROM Vals