User Defined Function (UDF) to Determine if a String is a Palindrome

Palindrome is a word or a phrase that reads the same in both directions. To check if a string is a palindrome in SQL Server, you can use REVERSE built in string function that returns the reverse order of a string value, and compare it to the original string.
We will create a User Defined Function (UDF) that accepts a string and checks if the string (with spaces removed from it) is a palindrome:

CREATE FUNCTION ufnPalindromeCheck (@MyString nvarchar(256))
RETURNS varchar(50)
DECLARE @ReturnString varchar(50)
SET @ReturnString = CASE WHEN REVERSE (REPLACE(@MyString, ' ', '')) = (REPLACE(@MyString, ' ', ''))
THEN 'The string is a palindrome'
ELSE 'The string is NOT a palindrome'
RETURN @ReturnString

To use this user-defined function:

SELECT dbo.ufnPalindromeCheck ('Step on no pets')


SELECT dbo.ufnPalindromeCheck ('So many dynamos')


If the post helped you, please share it:
Pin It

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">