我不太确定你的 table1Col1 在这里发挥作用,所以下面可能不足以完全解决你的问题,但它应该让你开始:
首先你需要一个split 函数,例如:
CREATE FUNCTION dbo.Split (@Input NVARCHAR(MAX), @Delimiter NVARCHAR(1))
RETURNS @T TABLE (OutputValue NVARCHAR(MAX))
AS
BEGIN
WITH CTE AS
( SELECT [OutputValue] = SUBSTRING(@Input, 1, CHARINDEX(@Delimiter, @Input)),
[InputValue] = SUBSTRING(@Input, CHARINDEX(@Delimiter, @Input) + 1, LEN(@Input)) + ' '
UNION ALL
SELECT [OutputValue] = SUBSTRING([InputValue], 1, CHARINDEX(@Delimiter, [InputValue])),
[InputValue] = SUBSTRING([InputValue], CHARINDEX(@Delimiter, [InputValue]) + 1, LEN([InputValue]))
FROM CTE
WHERE LEN([InputValue]) > 0
)
INSERT @T
SELECT DISTINCT OutputValue
FROM CTE
RETURN;
END
然后你可以使用这样的东西:
DECLARE @T TABLE (Col1 NVARCHAR(MAX));
INSERT @T VALUES ('apples oranges grapes'), ('apples oranges'), ('apples strawberries');
DECLARE @StringToCheck NVARCHAR(MAX) = 'apples oranges bananas grapes'
SELECT Col1
FROM @T
CROSS APPLY dbo.Split(Col1, ' ') spl
LEFT JOIN dbo.Split(@StringToCheck, ' ') chk
ON chk.OutputValue = spl.OutputValue
GROUP BY Col1
HAVING COUNT(spl.OutputValue) = COUNT(chk.OutputValue)
或者如果您需要专门排除项目
DECLARE @T TABLE (Col1 NVARCHAR(MAX));
INSERT @T VALUES ('apples oranges grapes'), ('apples oranges'), ('apples strawberries');
DECLARE @StringToCheck NVARCHAR(MAX) = 'apples oranges bananas grapes',
@StringToExlude NVARCHAR(MAX) = 'strawberries grapes'
SELECT Col1
FROM @T
CROSS APPLY dbo.Split(Col1, ' ') spl
LEFT JOIN dbo.Split(@StringToCheck, ' ') chk
ON chk.OutputValue = spl.OutputValue
LEFT JOIN dbo.Split(@StringToExlude, ' ') exc
ON exc.OutputValue = spl.OutputValue
GROUP BY Col1
HAVING COUNT(spl.OutputValue) = COUNT(chk.OutputValue)
AND COUNT(exc.OutputValue) = 0