SQL Server:从动态值表中选择列不包含任何值的所有行

SQL Server:从动态值表中选择列不包含任何值的所有行,sql,sql-server,tsql,Sql,Sql Server,Tsql,我正在使用SQL Server 2016。我正在搜索TableA,希望它不要返回TableB中某个术语存在于TableA特定列中的任何行 假设我有以下示例表: DECLARE @SearchTerms TABLE (word NVARCHAR(10)) INSERT INTO @SearchTerms SELECT v FROM (VALUES ('ABC'), ('DEF')) vals(v) SELECT * FROM @SearchTe

我正在使用SQL Server 2016。我正在搜索TableA,希望它不要返回TableB中某个术语存在于TableA特定列中的任何行

假设我有以下示例表:

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。我想从表@MyStrings中选择*,其中字符串值不包含ABC或DEF

大概是这样的:

SELECT * 
FROM @MyStrings
WHERE string NOT LIKE (SELECT word FROM @SearchTerms)

如果搜索项不可为空,则可以使用
LIKE
左键连接搜索项,并对搜索项为空的所有行进行筛选

SELECT s.*
       FROM @mystrings s
            LEFT JOIN @searchterms t
                      ON s.string LIKE concat('%', t.word, '%')
       WHERE t.word IS NULL;

如果它们可以为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;

我想这会管用的!术语不能为空,但搜索术语表可能没有行,在这种情况下,它会返回@MyStrings表中的所有内容。这很聪明,我需要记住这种方法。