簡體   English   中英

SQL Server:從動態值表中選擇列不包含任何值的所有行

[英]SQL Server : select all rows where Column does not contain any value from dynamic table of values

我正在使用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。 我想select * from table @MyStrings中select * from table其中字符串值不包含ABC或DEF。

像這樣:

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

如果搜索項不可為空,則可以使用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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM