如何在表中找到缺少的id

时间:2011-07-25 08:16:58

标签: sql tsql sql-server-2008

我的列如下所示

SID101
SID102
SID103
SID105
SID107

在上述标准中,我需要找到错过的SID号码。订购时错过了SID104和SID 106.

我怎样才能找到错过的身份证号码。任何人都可以帮我找到它。

提前致谢。

5 个答案:

答案 0 :(得分:1)

如果您的表格包含长度超过1个项目的空白,您可以使用此查询:

declare @t table(s varchar(20))

insert @t values ('SID101'),('SID102'),('SID103'),('SID105'),('SID108');

with cte as
(
    select substring(t.s, 4, len(t.s)) [i]
    from @t t
)
select 'SID' + cast(m.number as varchar(20))
from master..spt_values m
left join cte c on c.i = m.number
where [Type] = 'P' 
    and m.number >= (select min(i) from cte) 
    and m.number <= (select max(i) from cte)
    and c.i is null

输出:

-----------------------
SID104
SID106
SID107

答案 1 :(得分:0)

这很难。与

SELECT COUNT(*),MAX(CAST(REPLACE(y.name,'SID','') AS INT)) AS col_max FROM
sys.objects x INNER JOIN sys.columns y ON x.object_id=y.object_id
WHERE x.name='<TABLE_NAME>'

你应该知道,缺少多少列(即COUNT(*)为5而col_max为107)

当你有一个表,其中只包含一列,所有可能的ID从1到最大(即100,101,102,103,104,...,132),那么你可以做

SELECT * FROM (
    SELECT CAST(REPLACE(y.name,'SID','') AS INT) AS col_id FROM
    sys.objects x INNER JOIN sys.columns y ON x.object_id=y.object_id
    WHERE x.name='<TABLE_NAME>'
) a
RIGHT JOIN <TABLE_IDS> b ON a.col_id=b.id
WHERE a.col_id IS NULL AND b.id<=(
    SELECT MAX(CAST(REPLACE(y.name,'SID','') AS INT)) AS col_max FROM
    sys.objects x INNER JOIN sys.columns y ON x.object_id=y.object_id
    WHERE x.name='<TABLE_NAME>'
)

编辑:抱歉,我刚才看到,这些值不是列名,而是值。我的解决方案将找到缺少的列名称

答案 2 :(得分:0)

这样的事情应该有效:

DECLARE @i INT;
SET @i = 100;

CREATE TABLE #idsToCheck (checkId varchar(100));

WHILE (@i < 200)
    BEGIN
        INSERT INTO #idsToCheck VALUES ('SID' + CONVERT(varchar(100), @i));
        SET @i = @i + 1;
    END

SELECT * FROM #idsToCheck itc
    LEFT OUTER JOIN MainTable mt ON itc.checkId = mt.realId
    WHERE mt.realId = NULL

DROP TABLE #idsToCheck

...其中MainTable是包含SID101SID102等列值的表格,MainTable.realId是包含这些ID的列。根据您要检查/到的SID,修改while循环条件中的@i初始值和数字。

答案 3 :(得分:0)

声明@St int             声明@end int

     set @st = CAST( (select RIGHT( max(data),4) from orderno)as int) 
     set @end = CAST( (select RIGHT( min(data),4) from orderno)as int)   

     create table #temp(data int)

    while(@St <= @end )
    begin
 insert into #temp values(@St)
 set @St = @St +1
   end

  select * from orderno 
  select * from #temp
 select data from #temp where data not in (select cast(RIGHT(data,4))

答案 4 :(得分:-1)

declare @t table(s varchar(20))

insert @t values ('SID101'),('SID102'),('SID103'),('SID105'),('SID107');

with cte as
(
    select substring(t.s, 4, len(t.s)) [i]
    from @t t
)

select 'SID' + cast(t1.i + 1 as varchar(20))
from cte t1
join cte t2 on t2.i > t1.i
    and not exists(
        select 1
        from cte c3
        where c3.i > t1.i and c3.i < t2.i
    )
where t2.i <> t1.i + 1

输出:

-----------------------
SID104
SID106