日期:2014-05-18  浏览次数:20459 次

如何查询已删除的主键,求简易方法
有个客户表,主键“编号”是以B0001开头,B是表示客户级别,因为一些原因,有些客户已经被除名或者级别变了而移走了记录,现在要查询在这个表里到底消去了几个客户记录,已经他们空出来的编号,其中末尾编号未知,不考虑最末尾编号的客户曾经消去的情况


------解决方案--------------------
测试数据
--------
create table #test( id varchar(5) primary key)
insert into #test
select 'b0001 '
union all
select 'b0002 '
union all
select 'b0003 '
union all
select 'b0011 '

SQL语句
----------
declare @t table (id int identity(1,1),c varchar(5))
insert into @t(c)
select top 9999 '0 ' from sysobjects a,syscolumns b
update @t set c= 'b '+right( '0000 '+convert(varchar(4),id),4)
select * from @t where c not in (select id from #test) and c <=(select max(id) from #test)


结果
-------
id c
----------- -----
4 b0004
5 b0005
6 b0006
7 b0007
8 b0008
9 b0009
10 b0010

(所影响的行数为 7 行)