[英]SQL Server : select all rows where Column does not contain any value from dynamic table of values
I'm using SQL Server 2016. I am searching TableA and want it to not return any rows where one of the terms from TableB exists in a particular column of TableA. 我正在使用SQL Server2016。我正在搜索TableA,并希望它不返回TableA的特定列中存在TableB之一的术语的任何行。
Assume I have the following sample tables: 假设我有以下示例表:
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
In table @SearchTerms
, I have ABC and DEF. 在表@SearchTerms
,我有ABC和DEF。 I want to select * from table
@MyStrings where string value does not contain ABC or DEF. 我想select * from table
@MyStrings中select * from table
其中字符串值不包含ABC或DEF。
Something like this: 像这样:
SELECT *
FROM @MyStrings
WHERE string NOT LIKE (SELECT word FROM @SearchTerms)
If the search terms aren't nullable, you can left join the search terms using LIKE
and filter for all rows, where the search term is null. 如果搜索项不可为空,则可以使用LIKE
保留搜索项的连接性,并过滤搜索项为null的所有行。
SELECT s.*
FROM @mystrings s
LEFT JOIN @searchterms t
ON s.string LIKE concat('%', t.word, '%')
WHERE t.word IS NULL;
If they are nullable excluding them in the ON
clause might work. 如果它们可以为空,则在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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.