Sample Header Ad - 728x90

Looping through string, adding all numbers e.g. '123' = 1+2+3, demo with working loop included

0 votes
1 answer
7406 views
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
Asked by Peter PitLock (1405 rep)
Feb 24, 2014, 01:29 PM
Last activity: Feb 24, 2014, 01:43 PM