I have a basic while loop but I need to be able to increment the counter from one alpha character to the next:
declare @.counternvarchar(10)
set @.counter='A'
while @.counter<'Z'
begin
print'the counter is '+ @.counterset @.counter= @.counter+ @.counter
end
In this example I would need to see the following output:
the counter is A
the counter is B
the counter is C
the counter is D
....
Is this possible in SQL?
Yes, of course, just like you would in most other languages. Either use an integer that represents the ascii value of the letter, increment by one in the loop, and when you need to reference it, use CHAR(@.counter)...
SET @.counter=Ascii('A')
WHILE @.counter<=Ascii('Z')
BEGIN
PRINT CHAR(@.counter)
SET @.counter=@.counter+1
END
Or use an integer, that is the index into a string that contains all the letters you want...
SET @.Letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
SET @.counter=0
WHILE @.counter<length(@.Letters)
BEGIN
PRINT SUBSTRING(@.Letters,@.counter,1)
SET @.counter=@.counter+1
END
Or... use what you had and use the @.counter to store the character you want, and use the following to increment it:
SET @.counter=CHAR(ASCII(@.counter)+1)
|||
Thanks!
No comments:
Post a Comment