sqlloopssas

Do Loop in SAS SQL for Creating Column


I am new to SAS and SQL. I have a task to create similar column but with different number.

For example: | DATE | NAME | A1 | A2 | A3 | B |

So I code in SAS like this

PROC SQL;
    CREATE TABLE TEST AS
    SELECT DATE, NAME,
           DO i = 1 to 3
             0 AS A&i.,
           END
           1 as B
    FROM SOURCE;
QUIT;

When I run, I got this error

Syntax error, expecting one of the following: !, !!, &, (, *, **, +, ',', -, '.', /, <, <=, <>, =, >, >=, AND, EQ, 
               EQT, GE, GET, GT, GTT, LE, LET, LT, LTT, NE, NET, OR, ^=, |, ||, ~=.  

I appreciate any kind of help. Thank you.


Solution

  • I think you should use macro code to generate column names depend on loop counter. For example, in your case:

    %macro create_table(); %macro d; %mend d;
    
    PROC SQL;
        CREATE TABLE TEST AS
        SELECT DATE, NAME,
               %DO i = 1 %to 3;
                 0 AS A&i.,
               %END;
               1 as B
        FROM SOURCE;
    QUIT;
    
    %mend create_table;
    
    %create_table();
    

    Output:

    +-------+------+----+----+----+---+
    | date  | name | A1 | A2 | A3 | B |
    +-------+------+----+----+----+---+
    

    In addition, there is another way to complete task. Use data step instead of proc sql:

    data test(drop=i);
       set source;
       array a{3};
       do i=1 to 3;
          a{i} = 0;
       end;
       b=1;
    run;