'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
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Steve |
