有两张表,两张表只有一个字段TESTNO,所有数据都是5位,现在需要从A表中筛选出数据,这些数据具有的特征是连续的4位数在B表中没有此特征的数据(即B表中的数据没有连续的4位数和此条数据有相同特征),举例A表中23431,使用2343和3431在b表中找有没有含有2343和3431的数据,没有的话则插入C表
最好给出的是循环遍历的语句,因为AB两张表是动态的,定时会更新
a表
TESTNO
23431
12346
66547
54515
b表
TESTNO
42346
66548
62498
52922
查询出来的C表结果
23431
54515
------解决方案--------------------
这样不行吗:
select a.* from a where TESTNO not in(
select b.TESTNO from a,b
where left(cast(a.TESTNO as varchar(5)),4)=left(cast(b.TESTNO as varchar(5)),4)
)
干嘛要用循环遍历呢,你那表里会有数据插入的话,你循环的时候会锁表,插入不成功咋整嗫?或者说你循环的时候加了with nolock ,可以插入数据,但是会有脏读的哟
------解决方案--------------------
--> 测试数据: [a]
if object_id('[a]') is not null drop table [a]
create table [a] ([TESTNO] int)
insert into [a]
select 23431 union all
select 12346 union all
select 66547 union all
select 54515
--select * from [a]
--> 测试数据: [b]
if object_id('[b]') is not null drop table [b]
create table [b] ([TESTNO] int)
insert into [b]
select 42346 union all
select 66548 union all
select 62498 union all
select 52922
--select * from [b]
select *
from a
except
select a.*
from b join a on b.testno like '%'+LEFT(a.testno,4)+'%' or b.testno like '%'+right(a.testno,4)+'%'
23431
54515
------解决方案--------------------
你写的太麻烦了,一句not exists 就可以
------解决方案--------------------
not in和not exists性能上没太大差异。一句 not exists 也可以:
select a.TESTNO from a
where left(cast(a.TESTNO as varchar(5)),4) not exists(select left(cast(b.TESTNO as varchar(5)),4) from b)
------解决方案--------------------
So Easy 一条语句搞定,楼主给分
SELECT TESTNO FROM A
WHERE NOT EXISTS (
SELECT TESTNO FROM B
WHERE LEFT(B.TESTNO,4)<>LEFT(A.TESTNO,4) AND RIGHT(B.TESTNO,4)<>RIGHT(A.TESTNO,4)
)
------解决方案--------------------
俺只赞2楼,其它的真对吗?
------解决方案--------------------
看清楚条件,举例说明abcde是否有子字符串包含在edcba中,要取abcd比较edcb和dcba,还要取bcde比较edcb和dcba,上述各位的条件都不正确啊
------解决方案--------------------
select a.testno from #b b
right join #a a on charindex(substring(a.testno,1,4),b.testno)>0 or
charindex(substring(a.testno,2,4),b.testno)>0
where b.testno is null
------解决方案--------------------
select * from #b
create table #a(testno char(5))
insert into #a
select '23431' union
select '12346' union
select '66547' union
select '54515'
create table #b(testno char(5))
insert into #b
select '42346' union
select '66548' union
select '62498' union
select '52922'
select a.testno from #b b
right join #a a on charindex(substring(a.testno,1,4),b.testno)>0 or
charindex(substring(a.testno,2,4),b.testno)>0
where b.testno is null