如何找到 sql 中的最后一个序号?

How find last number of sequence numbers in sql?

我想在 sql 查询中找到序列的最后一个数字以自动填充建议字段值。例如我的代码字段(列)是:1,2,3,4,10,20 所以我想在我的查询中找到 4

如果您的 table 被称为 table_name 并且看起来像这样:

id
1
2
3
4
10
20

那么这应该可行:

select min(previd) from 
(select id, lag(id) over(order by id) as previd
from table_name) t
where id - previd > 1;

Fiddle

如果列的值是例如“1,2,3,4,6,8,0”,那么您可以使用函数从字符串中包含的序列中获取最后一个值。

create function dbo.FindLastNumberInSequence 
(
    @Delimited varchar(MAX),
    @Delimiter varchar(50) = ','
)
returns int as
begin
    declare @i int 
    declare @current int
    declare @previous int
    declare @sequenceFound bit = 0

    set @Delimited = @delimiter + @Delimited + @delimiter
    set @i = 1

    while   @i < LEN( @Delimited )
    begin
        set @current = SUBSTRING( @Delimited, @i+1, CHARINDEX( @Delimiter, @Delimited, @i+1 ) - @i-1 )

        if(@sequenceFound=1)
            if (@current != @previous + 1)
                break

        if (@current = @previous + 1)
            set @sequenceFound = 1

        set @previous = @current

        set @i = CHARINDEX( @Delimiter, @Delimited, @i+1 )
    end
    if(@sequenceFound=0)
        set @previous=-1
    return @previous
end

select dbo.FindLastNumberInSequence ('1,2,3,4,10,20', ',')  -- 4
select dbo.FindLastNumberInSequence ('9,8,1,2,3,4,10,20', ',') -- 4
select dbo.FindLastNumberInSequence ('9,8,1,13,4,10,20', ',')  -- -1 (no sequence found)