SQL SERVER – User Defined Functions (UDF) to Reverse String – UDF_ReverseString

UDF_ReverseString
UDF_ReverseString User Defined Functions returns the Reversed String starting from certain position.
First parameters takes the string to be reversed.
Second parameters takes the position from where the string starts reversing.

Script of UDF_ReverseString function to return Reverse String.
CREATE FUNCTION UDF_ReverseString
( @StringToReverse VARCHAR(8000),
@StartPosition INT )
RETURNS VARCHAR(8000)
AS
BEGIN
IF
(@StartPosition <= 0)
OR (
@StartPosition > LEN(@StringToReverse))
RETURN (REVERSE(@StringToReverse))
RETURN (STUFF (@StringToReverse,
@StartPosition,
LEN(@StringToReverse) - @StartPosition + 1,
REVERSE(SUBSTRING (@StringToReverse,
@StartPosition
LEN(@StringToReverse) - @StartPosition + 1))))
END
GO

Usage of above UDF_ReverseString:

Reversing the string from third position
SELECT dbo.UDF_ReverseString('forward string',3)
Results Set : forgnirts draw

Reversing the entire string passing 0 as beginning character
SELECT dbo.UDF_ReverseString('forward string',0)
Results Set : gnirts drawrof

Reversing the entire string passing negative number as beginning character
SELECT dbo.UDF_ReverseString('forward string',-9)
Results Set : gnirts drawrof

Reversing the entire string passing larger number than string length as beginning character
SELECT dbo.UDF_ReverseString('forward string',900)
Results Set : gnirts drawrof

SQL SERVER has REVERSE Function which is used in UDF above.
If you have to reverse complete string. I would rather suggest use following script rather than using the UDF above. The purpose of the UDF is to reverse the string from certain positioned characters only.

Example for REVERSE function in SQL SERVER 2005 from BOL:
USE AdventureWorks;
GO
SELECT FirstName, REVERSE(FirstName) AS REVERSE
FROM Person.Contact
WHERE ContactID < 5
ORDER BY FirstName;
GO

FirstName Reverse
————– ————–
Catherine enirehtaC
Gustavo ovatsuG
Humberto otrebmuH
Kim miK
(4 row(s) affected)

Reference : Pinal Dave (https://blog.sqlauthority.com)

SQL Function, SQL Scripts, SQL String
Previous Post
SQL SERVER – Copy Column Headers in Query Analyzers in Result Set
Next Post
SQL SERVER – 2005 TOP Improvements/Enhancements

Related Posts

Leave a Reply