我正在使用SQL Server2016。我正在搜索TableA,并希望它不返回TableA的特定列中存在TableB中的一项术语的任何行。
假设我有以下示例表:
DECLARE @SearchTerms TABLE (word NVARCHAR(10))
INSERT INTO @SearchTerms
SELECT
v
FROM
(VALUES ('ABC'), ('DEF')) vals(v)
SELECT * FROM @SearchTerms
DECLARE @MyStrings TABLE
(
ID INT,
string NVARCHAR(MAX)
)
INSERT INTO @MyStrings
SELECT
v, x
FROM
(VALUES (1, 'This is the first sentence and has nothing'),
(2, 'This is the second sentence and has ABC only'),
(3, 'This is the third sentence and has DEF only'),
(4, 'This is the fourth sentence and has ABC and DEF together')) vals(v,x)
SELECT * FROM @MyStrings
在表@SearchTerms
中,我有ABC和DEF。我要在字符串值不包含ABC或DEF的select * from table
@MyStrings中。
类似这样的东西:
SELECT *
FROM @MyStrings
WHERE string NOT LIKE (SELECT word FROM @SearchTerms)
答案 0 :(得分:3)
如果搜索项不能为空,则可以使用LIKE
保留搜索项的联接,并过滤搜索项为null的所有行。
SELECT s.*
FROM @mystrings s
LEFT JOIN @searchterms t
ON s.string LIKE concat('%', t.word, '%')
WHERE t.word IS NULL;
如果它们可以为空,则可以将它们排除在ON
子句中。
SELECT s.*
FROM @mystrings s
LEFT JOIN @searchterms t
ON s.string LIKE concat('%', t.word, '%')
AND t.word IS NOT NULL
WHERE t.word IS NULL;