With T-SQL, I'm trying to find the easiest way to reverse numbers in string. so for string like Test123Hello
have Test321Hello
.
[Before] [After]
Test123Hello Test321Hello
Tt143 Hello Tt341 Hello
12Hll 21Hll
Tt123H3451end Tt321H1543end
you can use this function
CREATE FUNCTION [dbo].[fn_ReverseDigit_MA]
(
@Str_IN nVARCHAR(max)
)
RETURNS NVARCHAR(max)
AS
BEGIN
DECLARE @lenstr AS INT =LEN(@Str_IN)
DECLARE @lastdigend AS INT=0
while (@lastdigend<@lenstr)
BEGIN
DECLARE @strPart1 AS NVARCHAR(MAX)=LEFT(@Str_IN,@lastdigend)
declare @lenstrPart1 AS INT=LEN(@strPart1)
DECLARE @strPart2 AS NVARCHAR(MAX)=RIGHT(@Str_IN,@lenstr-@lastdigend)
declare @digidx as int=patindex(N'%[0-9]%' ,@strPart2)+@lenstrPart1
IF(@digidx=@lenstrPart1)
BEGIN
BREAK;
END
DECLARE @strStartdig AS NVARCHAR(MAX) = RIGHT(@Str_IN,@lenstr-@digidx+1)
declare @NDidx as int=patindex(N'%[^0-9]%' ,@strStartdig)+@digidx-1
IF(@NDidx<=@digidx)
BEGIN
SET @NDidx=@lenstr+1
END
DECLARE @strRet AS NVARCHAR(MAX)=LEFT(@Str_IN,@digidx-1) +REVERSE(SUBSTRING(@Str_IN,@digidx,@NDidx-@digidx)) +RIGHT(@Str_IN,@lenstr-@NDidx+1)
SET @Str_IN=@strRet
SET @lastdigend=@NDidx-1
END
return @Str_IN
END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With