从 Table 中的特定列提供 'like' 函数的值?

Provide the values for a 'like' function from a specific column in a Table?

我正在使用 SQL Server 2014,我需要一个 T-SQL 查询,该查询使用 like 函数对 [=37 的特定列 (c1) 运行 =] (t1) 以查明它是否包含另一个 Table (t2).

的 (c2) 列中找到的代码列表中的一个代码

为简化起见,这里是场景和预期输出:

Table t1:

ID       Notes
101      (free text in this column)
102      ...
...      ...
115000   ...

Table t2(300多个代码的列表):

Code
FR110419
GB150619
...
DE111219

我在找什么:

SELECT ID 
FROM t1
WHERE t1.Notes like (SELECT Code FROM t2)

由于 like 运算符需要 '%' 才能工作,我对如何构造该行感到困惑。

我对 Whosebug 做了一些研究,我遇到的最接近的解决方案是 mysql 问题:how to use LIKE with column name

我们将不胜感激任何类型的帮助。

您似乎在寻找 JOIN:

SELECT ID 
FROM t1
INNER JOIN t2 ON t1.Notes LIKE '%' + t2.Code + '%'

如果不同的 Code 可能出现在相同的 Note 中,使用带有相关子查询的 EXISTS 条件也是一种选择,因为它可以避免在输出中重复记录:

SELECT ID
FROM t1
WHERE EXISTS (
    SELECT 1 FROM t2 WHERE t1.Notes LIKE '%' + t2.Code + '%'
)

您可以像这样将 cross applycharindex 一起使用:

--Loading data
create table t1 (id varchar(10));
insert into t1 (id) values ('100100'),('200100'),('300100')
insert into t1 (id) values ('100200'),('200200'),('300200')
insert into t1 (id) values ('100300'),('200300'),('300300')
insert into t1 (id) values ('0100'),('0200'),('0300')
insert into t1 (id) values ('00010'),('00020'),('00030')

create table t2 (id varchar(10));
insert into t2 (id) values ('020'),('010')

select t.id
from t1 as t
cross apply t2 as t2
--where charindex(t2.id,t.id) > 0 -- simulates a double % one at the beginning and one at the end
--where charindex(t2.id,t.id) = 1 -- simulates a % at the beginning
where charindex(t2.id,t.id) = len(t.id)-len(t2.id)+1 -- simulates a % at the end

唯一的问题是 table 非常大,这可能是一个缓慢的解决方案。

在已经发布的内容的基础上,您可以创建索引视图来真正加快速度。

使用 CTE6 的示例数据...

--Loading data
create table t1 (id varchar(10));
insert into t1 (id) values ('100100'),('200100'),('300100')
insert into t1 (id) values ('100200'),('200200'),('300200')
insert into t1 (id) values ('100300'),('200300'),('300300')
insert into t1 (id) values ('0100'),('0200'),('0300')
insert into t1 (id) values ('00010'),('00020'),('00030')

create table t2 (id varchar(10));
insert into t2 (id) values ('020'),('010')
GO

--  The View
CREATE VIEW dbo.vw_t1t2 WITH SCHEMABINDING AS
SELECT     t1 = t1.id, t2 = t2.id, cb = COUNT_BIG(*)
FROM       dbo.t1 AS t1
CROSS JOIN dbo.t2 AS t2
WHERE      CHARINDEX(t2.id,t1.id) > 0
GROUP BY   t1.id, t2.id
GO
-- The index (may need to add something else to make UNIQUE)
CREATE UNIQUE CLUSTERED INDEX uq_cl_vwt1t2 ON dbo.vw_t1t2(t1,t2);
GO

这对于 SELECT 语句将执行得很好,但可能会影响针对 t1 和 t2 的数据修改,因此请确保使用尽可能小的数据类型,并且只包含您确定需要的列(Varchar(10) 是好的)。我包括 COUNT_BIG() 是因为它在利用 GROUP BY 的索引视图中是必需的。