sql create a variable in select

Solutions on MaxInterview for sql create a variable in select by the best coders in the world

showing results for - "sql create a variable in select"
Lilli
29 Aug 2018
1-- Create the table.
2CREATE TABLE TestTable (cola int, colb char(3));
3GO
4SET NOCOUNT ON;
5GO
6-- Declare the variable to be used.
7DECLARE @MyCounter int;
8
9-- Initialize the variable.
10SET @MyCounter = 0;
11
12-- Test the variable to see if the loop is finished.
13WHILE (@MyCounter < 26)
14BEGIN;
15   -- Insert a row into the table.
16   INSERT INTO TestTable VALUES
17       -- Use the variable to provide the integer value
18       -- for cola. Also use it to generate a unique letter
19       -- for each row. Use the ASCII function to get the
20       -- integer value of 'a'. Add @MyCounter. Use CHAR to
21       -- convert the sum back to the character @MyCounter
22       -- characters after 'a'.
23       (@MyCounter,
24        CHAR( ( @MyCounter + ASCII('a') ) )
25       );
26   -- Increment the variable to count this iteration
27   -- of the loop.
28   SET @MyCounter = @MyCounter + 1;
29END;
30GO
31SET NOCOUNT OFF;
32GO
33-- View the data.
34SELECT cola, colb
35FROM TestTable;
36GO
37DROP TABLE TestTable;
38GO
39
similar questions
queries leading to this page
sql create a variable in select