2014-04-29 43 views
2

我工作的SQL Server 2012年SQL - 比较Table1.items(NTEXT)到Table2.item(VARCHAR)

我想从表1分裂的不同项目与特定的列进行比较表2。

表1有一排这样的:

| id |   items   | 
| 1  | aaa;ery;sha;cbre;dezrzyg; | 
| 2  | aaa;ery;sha;cbre;dezrzyg; | // Could be the same items than another row 
| 3  | dg;e3ry;sd6ha;cb8re;48dz; | 
| 4  | e5zeza;48;dz;46az;12BREd; | 
| ... |   ...    | 
| 10 |   aaa    | // Currently match because the request compare the whole cell 

项目是一个字符串(ntext在DB)和字符串不会包含空格。

表2有一排这样的:

| id |   item   | 
| 1  |   aaa    | // match 
| 2  |   AAA    | // match 
| 3  |   aaa52   | // doesn't match 
| 4  |   2aaa2   | // doesn't match 
| ... |   ...    | 

项目也是一个字符串(nvarchar在DB)和从不包含空格的字符串。

这里是我当前的SQL请求:

SELECT * FROM Table1 t1 
INNER JOIN Table2 t2 ON t1.items = t2.item 

我怎么能解决我的问题? 我应该分割一个字符串,然后比较每个Table1.itemsTable2.item? SQL中有什么可以轻松解决的吗?

回答

3

SQL中是否有某些东西可以轻松解决它?

不,但您可以创造性地使用like。当你做这样的事情时,索引不能帮你提高性能。

select * 
from Table1 as T1 
    inner join Table2 as T2 
    on ';'+cast(T1.items as nvarchar(max))+';' like '%;'+T2.item+';%' 

SQL Fiddle

0

故障安全的解决方案是分裂items列的内容转换成台状形式,然后其加入到表2。

说我们有这些表:

create table #t1 (id int, items varchar(100)); 
go 
insert #t1 values 
(1, 'aaa;ery;sha;cbre;dezrzyg;'), 
(2, 'aaa;ery;sha;cbre;dezrzyg;'), 
(3, 'dg;e3ry;sd6ha;cb8re;48dz;'), 
(4, 'e5zeza;48;dz;46az;12BREd;'), 
(10, 'aaa'); 
go 

create table #t2 (id int, item varchar(100)); 
go 
insert #t2 values 
(1, 'aaa'), 
(2, 'AAA'), 
(3, 'aaa52'), 
(4, '2aaa2') 
go 

我们将使用下面的方法来拆分items

select substring(items, n, charindex(';', items + ';', n) - n) 
from numbers, #t1 
where substring(';' + items, n, 1) = ';' 
and n < len(items) + 1 

这需要numbers表,看here如何创建它。

这里是整个查询:

select distinct #t1.id, #t1.items, case when #t2.id is null then 'doesn''t match' else 'match' end 
from #t1 
cross apply (
    select substring(items, n, charindex(';', items + ';', n) - n) 
    from numbers 
    where substring(';' + items, n, 1) = ';' 
    and n < len(items) + 1 
) x (col) 
left join #t2 on x.col = #t2.item 
--where #t2.id is not null 
相关问题