Monday, April 22, 2013

Check String is PalinDrome in SQL Server

How to  Check String is Palindrome in SQL Server 2012


--Insert Palindrome String here
declare @string varchar(50)=UPPER(N'ab ba');

--Find Length of the String using len
declare @length int  = len(@string);

--Find Middle Position of the String
declare @middle int = @length/2 ;

--This is required because Splitting the String into 2 pieces.
--first portion in @first last portion in @last variable.
declare @first varchar(25),@last varchar(25);

--Store first half of the String here
SELECT @first=SUBSTRING(@string,1,@middle)

-- Here logic comes
--IF string length is ODD then increment by 1
--else increment by 2, because leaving alone the exact middle letter in the String

if ( @length%2 = 0)
      set @middle = (@length/2)+1;
else set @middle = (@length/2)+2;
--Store next half string and reverse it
select @last=Reverse(SUBSTRING(@string,@middle,@length));

--testing purpose
SELECT @FIRST,@LAST,@MIDDLE,@length;

--Compare 2 Strings if they are equal or not

if( @first = @last)
  print 'both are equal ==> String is Palindrome';
else  print 'both are different ==> String is not Palindrome';


Tags: Palindrome in SQL Server , Palindrome in T-SQL, Check String is Palindrome in SQL-Server,
How to Check String is Palindrome or not in SQL Server, SQL Server String comparisions,

No comments:

Post a Comment