BookmarkSubscribeRSS Feed
deleted_user
Not applicable
I'm trying to run a piece of code X number of times returning a separate dataset for the last X months. Can I use do, to and end outside of the datastep, but inside a macro? It doesn't seem to work.



%macro test(period);

%do i=1 %to .

data _null_;
call symput ('position', i);
run;

%let posdate=INTnx('MONTH',today(),-&position);

data pos&position;
set inputdata;
where timeid=&posdate;
run;

proc sort data=pos&position;
by accountid;
run;

%end;

%mend;

%test(12);
1 REPLY 1
deleted_user
Not applicable
cstayner,

You're nearly there. I'd make a few changes:

Your null data step is the right idea, but I'd avoid adding a variable that doubles up on i, you could get the data step doing some work, and move the posdate calculation here:

data _null_;
call symput ('posdate', INTnx('MONTH',today(),-&i));
run;

This would be quite a bit better - the way you have written the posdate assignment will have problems because the intnx() and today() functions are not macro functions. The alternative would be:

%let posdate=%sysfunc(INTnx('MONTH',%sysfunc(today()),-&position));

In this case I'd be inclined, though, to restructure the code, see below:

data have(keep=account_id time_id);
do t = 0 to 11;
do account_id = 12 to 1 by -1;
time_id = intnx('month', '01Jan2008'd, t);
output;
end;
end;
run;

%macro sortseg(months=12);

proc sort
data = have
;
by account_id
;
run;

/* Create the macro variables we want, one set for months, one for datasets */
data _null_;
do m = 1 to &months;
call symput('month_'||compress(m), compress(intnx('month', '01Jan2009'd, -m)));
call symput('ds_out_'||compress(m), 'want_'||compress(m));;
end;
run;
/* Specify multiple output datasets */
data
%do month_loop = 1 %to &months;
&&ds_out_&month_loop
%end;
;
set have;
/* Use if, rather than where, to conditionally output */
%do month_loop = 1 %to &months;
if time_id = &&month_&month_loop then output &&ds_out_&month_loop;
%end;
run;

%mend;

%sortseg(months=12)

The macro code is writing the SAS code, rather than executing the process, and this is one of the key things to remember about how macro and SAS code interact.

I hope this helps,

ProcMe

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

Register now

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 1 reply
  • 1174 views
  • 0 likes
  • 1 in conversation