差距和岛屿SQL错误

时间:2014-12-17 19:38:51

标签: sql sql-server integer-overflow gaps-and-islands

尝试运行查询以识别表格中的间隙和岛屿的开始和停止。我应用了一个我认为适用于我的数据集但我无法正常运行的查询。运行此代码时出现转换错误:

select start, stop 
from (
select m.API_WellNo + 1 as start,
    (select min(API_WellNo) - 1 
    from tblWellMaster x 
    where x.API_WellNo > m.API_WellNo) as stop
from tblWellMaster m    left outer join tblWellMaster r on m.API_WellNo = r.API_WellNo - 1
where r.API_WellNo is null
  ) as x
where stop is not null;

这是我得到的错误: nvarchar值的转换' 31003022850000'溢出了一个int列。

我无法弄清楚这个int列的来源,因为我的API_WellNo是一个nvarchar(14)

该号码是构成序列的id之一,我正在尝试找到差距/岛屿,非常感谢任何帮助,谢谢

1 个答案:

答案 0 :(得分:2)

试试这个:

with cte as (
  select start = (cast(m.API_WellNo as bigint) + 1)
      , [stop] = ca.[stop]
    from tblWellMaster m    
      cross apply (
        select top 1 [stop]=(cast(x.API_WellNo as bigint) -1)
          from tblWellMaster x 
          where x.API_WellNo > m.API_WellNo
          order by x.API_WellNo
        ) as ca
    where not exists (
      select 1 
        from tblWellMaster r 
        where cast(m.API_WellNo as bigint)  = (cast(r.API_WellNo as bigint)  - 1))
  )
  select start, [stop] 
    from cte 
    where [stop] is not null;