Home Forums Programming General Reverse string without built in functions RE: Reverse string without built in functions

  • Here's another method:

    -- Parameters

    DECLARE @String VARCHAR(8000)

    SET @String = 'Reverse'

    -- Local Variables

    DECLARE @OutputString VARCHAR(8000); SET @OutputString = '';

    DECLARE @StrLen INT; SET @StrLen = DATALENGTH(@String);

    DECLARE @MappingTable TABLE (n INT PRIMARY KEY CLUSTERED);

    INSERT INTO @MappingTable (n)

    SELECT TOP(@StrLen) n = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM syscolumns a, syscolumns b;

    UPDATE @MappingTable SET @OutputString = @OutputString + SUBSTRING(@String,(@StrLen+1)-n,1);

    SELECT FormattedAmount = @OutputString;

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden