by Maeenul
21. January 2012 11:58
A palindrome is a word, phrase, number, or other sequence of units that can be read the same way in either direction. Some simple example of palindrome are
1. Malayalam
2. Amma
3. Appa
4. Madam
5. Racecar
To check whether a string is palindrome or not is very easy. We can create a function as follows:
CREATE FUNCTION dbo.IsPalindrome (@str varchar(50))
RETURNS int
AS
BEGIN
if REVERSE(@str) = @str
return (1)
return (0)
END;
GO
SELECT dbo.IsPalindrome('Malayalam') -- this is a palindrome
SELECT dbo.IsPalindrome('Amma') -- this is a palindrome
SELECT dbo.IsPalindrome('Appa') -- this is a palindrome
SELECT dbo.IsPalindrome('Hey') -- this is not a palindrome
SELECT dbo.IsPalindrome('Hola') -- this is not a palindrome
SELECT dbo.IsPalindrome('Ammaa') -- this is not a palindrome
The above function returns 1 if the string is a palindrome and returns 0 is the string is not a palindrome.
To check whether a string is palindrome or not, we just need to reverse the string and check whether the reversed string is equal to the original string or not. As we know, in T-SQL we have a REVERSE function, this is actually a very easy task to do in SQL.