Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through a macro variable in SAS

Tags:

sas

I have an example like this:

proc sql;
select dealno into :deal_no 
from deal_table; 

Now I want to traverse the variable deal_no now containing all dealno in table deal_table but I don't know how to do it.

like image 746
trisas Avatar asked Dec 11 '22 20:12

trisas


2 Answers

Another option is add 'separated by' to the sql code, which will add a delimiter to the values. You can then use the SCAN function in a data step or %SCAN in a macro to loop through the values and perform whatever task you want. Example below.

proc sql noprint;
select age into :age separated by ','
from sashelp.class;
quit;

%put &age.;

data test;
do i=1 by 1 while(scan("&age.",i) ne '');
    age=scan("&age.",i);
    output;
end;
drop i;
run;
like image 138
Longfish Avatar answered Jan 01 '23 21:01

Longfish


If you do

%put &deal_no;

you can see that it only contains the first value of dealno, not all of them. To avoid that you can do something like this:

proc sql;
    create table counter as select dealno from deal_table;
    select dealno into :deal_no_1 - :deal_no_&sqlobs
    from deal_table;
quit;

%let N = &sqlobs;

%macro loop;
%do i = 1 %to &N;
    %put &&deal_no_&i;
%end;
%mend;

%loop; run;
like image 40
Dejan Peretin Avatar answered Jan 01 '23 20:01

Dejan Peretin