reverse string

We have a string, such as:

DECLARE @Source VARCHAR(MAX)= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'


Now I want to reverse it:

ZYXWVUTSRQPONMLKJIHGFEDCBA


At this point, you can write a method to handle:

 

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:      Insus.NET
-- Create date: 2019-05-16
-- Update date: 2019-05-16
-- Description: Reverse character
CREATE FUNCTION [dbo].[svf_ReverseString] ( 
     @Source VARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
   DECLARE @Destination VARCHAR(MAX) = ''
    WHILE LEN(@Source) > 0
        BEGIN
        IF LEN(@Source) = 0
        BEGIN
            SET @Destination = @Source + @Destination
            SET @Source = ''
        END
        ELSE
        BEGIN
            SET @Destination = SUBSTRING(@Source, 1, 1) + @Destination
            SET @Source = SUBSTRING(@Source, 2, LEN(@Source))
        END
    END

RETURN @Destination
END
GO
Source Code

 

For example, run the above method:

 

 

Ha ha, everything is in vain, because Microsoft has provided a modern method, REVERSE:

 

No matter which method is above, reverse the following situation, I wonder if it is OK? The string is reversed with a space as the word.

 

 

Therefore, another method has to be written to deal with:

 

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:      Insus.NET
-- Create date: 2019-05-16
-- Update date: 2019-05-16
-- Description: Inversion function
CREATE FUNCTION [dbo].[svf_Reverse] ( 
     @Source VARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN 
    DECLARE @Destination VARCHAR(MAX) = ''
        
    WHILE LEN(@Source) > 0
      BEGIN
        IF CHARINDEX(' ', @Source) > 0
        BEGIN
            SET @Destination = SUBSTRING(@Source, 0, CHARINDEX(' ', @Source)) + ' ' + @Destination
            SET @Source = LTRIM(RTRIM(SUBSTRING(@Source, CHARINDEX(' ', @Source) + 1, LEN(@Source))))
        END
        ELSE
        BEGIN
            SET @Destination = @Source + ' ' + @Destination
            SET @Source = ''
        END
      END
RETURN @Destination
END
GO
Source Code

Tags: SQL Sever

Posted on Sat, 09 Nov 2019 11:02:58 -0500 by Andrew B