2015-08-08 51 views
0

我知道我们可以使用LIKE进行模式匹配,但是,这里是要做的。匹配表中的任何图案?

我有一个表,其中有一列,“模式”,该值是这样的:

host1% 
%host2 
.... 

我还有一个表,其中有一列,“主机”。问题是:如何检查'Host'表中的值是否与'Pattern'中的任何模式不匹配?

如果它太复杂,那么一个简化的问题是:如何检查'Host'中的值是不是StartWith'Pattern'中的任何字符串?

我们可以使用循环,但有没有更好的方法?理想情况下,它应该为ql服务器2008工作,但最新版本会做。

感谢

回答

2

使用where not exists接着,检查针对包含数据的表的当前行的每个图案的子查询。即

where not exists 
(
    select top 1 1 
    from @patterns p 
    where d.datum like p.pattern 
) 

完整代码工作实例:SQL Fiddle

declare @patterns table 
(
    pattern nvarchar(16) not null 
) 
declare @data table 
(
    datum nvarchar(16) not null 
) 
insert @patterns 
values ('host1%') 
,('%host2') 
insert @data 
values ('host1234') 
, ('234host1') 
, ('host2345') 
, ('345host2') 

select * 
from @data d 
where not exists 
(
    select top 1 1 
    from @patterns p 
    where d.datum like p.pattern 
) 
+0

这将有助于有别名 – Bulat

+0

@Bulat;好喊;只是懒惰;现在用别名进行修改以提高清晰度。 – JohnLBevan

1
select t1.host 
from table_1 t1 
left join table_2 t2 on t1.host like t2.pattern 
where t2.pattern is null