![](/img/trans.png)
[英]Select matching rows from a table where either one of two columns contain any value from a list of values
[英]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.