如何确定搜索字符串是否在几列中

时间:2018-04-23 23:37:56

标签: sql sql-server

SELECT *
FROM [FirstTable] as A
JOIN [SecondTable] as B on A.ID = B.ID
WHERE (NOT B.column1 LIKE '%'+ A.someCol + '%')
AND (NOT B.column2 LIKE '%'+ A.someCol + '%')

“LIKE”旁边有“NOT”,但也没用。另外,我想确保不区分大小写这是对的吗?我正在寻找来自A的所有文件,其中值A.someCol没有出现在B.column1或B.column2中的任何地方

例如

A.someCol 'substr'
B.column1 'test'
B.column2 'test2'

上面应该返回带有这些值的行。

A.someCol 'substr'
B.column1 'test'
B.column2 'testsubstrtest'

上述内容不应返回包含这些值的行。

1 个答案:

答案 0 :(得分:1)

您可以使用CHARINDEX来解决此问题:

SELECT *
FROM [FirstTable] as A
JOIN [SecondTable] as B ON A.ID = B.ID
WHERE CHARINDEX(A.someCol, B.column1) = 0 
    AND CHARINDEX(A.someCol, B.column2) = 0

您还可以指定搜索case-sensitivecase-insensitive

SELECT *
FROM [FirstTable] as A
JOIN [SecondTable] as B ON A.ID = B.ID
WHERE CHARINDEX(A.someCol, B.column1 COLLATE Latin1_General_CI_AS) = 0 
    AND CHARINDEX(A.someCol, B.column2 COLLATE Latin1_General_CI_AS) = 0

它如何处理NULL?

  

如果 expressionToFind expressionToSearch 为NULL,则CHARINDEX将返回NULL。

在这种情况下,您可以使用ISNULL

使用以下解决方案之一
SELECT *
FROM [FirstTable] as A
JOIN [SecondTable] as B ON A.ID = B.ID
WHERE ISNULL(CHARINDEX(A.someCol, B.column1), 0) = 0 
    AND ISNULL(CHARINDEX(A.someCol, B.column2), 0) = 0

...或

SELECT *
FROM [FirstTable] as A
JOIN [SecondTable] as B ON A.ID = B.ID
WHERE CHARINDEX(ISNULL(A.someCol, ''), ISNULL(B.column1, '')) = 0 
    AND CHARINDEX(ISNULL(A.someCol, ''), ISNULL(B.column2, '')) = 0