And if you must use a loop then how about this?
declare @Str1 varchar(10) = 'ABBA';
declare @IsPalindrome bit = 1;
declare @LoopCnt int = 0;
while @LoopCnt < len(@Str1) and @IsPalindrome = 1
begin
select @IsPalindrome = case when substring(@Str1,1 + @LoopCnt,1) = substring(@Str1,len(@Str1) - @LoopCnt,1) then 1 else 0 end;
set @LoopCnt = @LoopCnt + 1;
end
if @IsPalindrome = 1
print @Str1 + ' is a palindrome'
else
print @Str1 + ' is not a palindrome'
set @LoopCnt = 0;
set @IsPalindrome = 1;
set @Str1 = 'ABC';
while @LoopCnt < len(@Str1) and @IsPalindrome = 1
begin
select @IsPalindrome = case when substring(@Str1,1 + @LoopCnt,1) = substring(@Str1,len(@Str1) - @LoopCnt,1) then 1 else 0 end;
set @LoopCnt = @LoopCnt + 1;
end
if @IsPalindrome = 1
print @Str1 + ' is a palindrome'
else
print @Str1 + ' is not a palindrome'
set @LoopCnt = 0;
set @IsPalindrome = 1;
set @Str1 = 'ABA';
while @LoopCnt < len(@Str1) and @IsPalindrome = 1
begin
select @IsPalindrome = case when substring(@Str1,1 + @LoopCnt,1) = substring(@Str1,len(@Str1) - @LoopCnt,1) then 1 else 0 end;
set @LoopCnt = @LoopCnt + 1;
end
if @IsPalindrome = 1
print @Str1 + ' is a palindrome'
else
print @Str1 + ' is not a palindrome'
You will also notice that I short circuit my loop to avoid unnecessary comparisons.