简体   繁体   中英

How find last number of sequence numbers in sql?

I want find last number of sequence in sql query for fill automatically suggestion field value. forexample my code field(column) is:1,2,3,4,10,20 so i want found 4 in my query

If your table is called table_name and looks like this:

id
1
2
3
4
10
20

Then this should work:

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

Fiddle

if the value of a column is for example '1,2,3,4,6,8,0' then you can use a function to get the last value from a sequence contained within a string.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM