This works to output the string 123456
as:
1
2
3
4
5
6
Code:
declare @string varchar(20)
declare @index int
declare @len int
declare @char char(1)
set @string = '123456'
set @index = 1
set @len= LEN(@string)
WHILE @index<= @len
BEGIN
set @char = SUBSTRING(@string, @index, 1)
print @char
SET @index= @index+ 1
END
But when I try to use this code to add those values up when looping through them (1+2+3+4+5+6 = 21), then I do no get a result from SQL, please help
declare @string varchar(20)
declare @index int
declare @len int
declare @char char(1)
set @string = '123456'
set @index = 1
set @len= LEN(@string)
declare @Total int
WHILE @index<= @len
BEGIN
set @char = SUBSTRING(@string, @index, 1)
set @Total = @Total + cast(@char as int)
SET @index= @index+ 1
END
print @Total