Technical Article

Calculate alphabetic sequence

,

/*

    For Testing script

    declare @x table (cod varchar(100))

    insert into @x (cod) select 'AAAAAAAA'

    declare @i int

    set @i = 0

    while @i<1000

    begin

        insert into @x (cod) select top 1 dbo.fn_Calc_AlfaSeq(cod) from @x order by cod desc

        set @i=@i+1

    end

    select * from @x

*/

if object_id(N'fn_Calc_AlfaSeq', N'FN') is not null
    drop function dbo.fn_Calc_AlfaSeq
go

CREATE FUNCTION dbo.fn_Calc_AlfaSeq(@in_cod VARCHAR(100))
RETURNS VARCHAR(100)
AS
BEGIN

declare @ret_codvarchar(100),
@l1char(1), 
@l2char(1), 
@l3char(1),
@iint,
@pint,
@asciiint,
@stopbit

declare @array table (id int, valor char(1))


set @i = 1
while @i<=len(@in_cod)
begin
insert into @array (id,valor) select @i, substring(@in_cod,@i,1)
set @i = @i+1
end

set @i = (select max(id) from @array)

set @stop = 0
while @i>=1 and @stop=0
begin
set @ascii = (select ascii(valor) from @array where id=@i)
if @ascii+1<91
begin
set @p=@i
set @stop = 1
end

set @i=@i-1
end

set @ret_cod = ''
select @ret_cod = @ret_cod + case when id<@p then valor else case when id=@p then char(ascii(valor)+1) else 'A' end end from @array order by id

return @ret_cod

END

go
GRANT  EXECUTE  ON dbo.fn_Calc_AlfaSeq TO [public]

Rate

2.5 (2)

You rated this post out of 5. Change rating

Share

Share

Rate

2.5 (2)

You rated this post out of 5. Change rating