This would be an ideal job for SAS/Macro, which allows text substitution into repeated code. See below for a solution (assuming a date range of 1991-2011, change the %let
statements to suit your range), with a macro %do
loop, which substitutes the value of &dt. (1991-2011) into the code provided in your question.
%macro date_export;
%let start_date = 1991;
%let end_date = 2011;
%do dt=&start_date %to &end_date;
proc export
data=ds (where=(year=&dt.)) outfile="ds&dt..csv" DBMS=CSV replace;
run;
%end;
%mend date_export;
%date_export
The macro
The date_export
macro is defined between the %macro
and %mend
statements. Firstly the date range is defined as two macro variables (this can be omitted and the variables plugged straight into the %do
statement, but is stated here for clarity). The %do
statement starts off a loop, with the dt
macro variable ranging between start_date
and end_date
. This could be rewritten as:
%do dt=1991 %to 2011;
and the initial two %let
statements omitted.
The loop runs all code between %do
and %end
, substituting values of dt
when it finds &dt.
.
Export code
There are a few subtle changes required to ensure the proc export
runs correctly inside the macro loop,
Firstly and most obviously I have substituted the year for &dt.
which passes the value of dt
into your code.
Note that when placed next to the .csv
an extra period is required (the first period resolves with the dt
, leaving just the single period and csv
behind).
The single quotes from your question need to be replaced with double-quotes, so that the macro will resolve. Otherwise the resulting file will be called literally 'ds&dt..csv'.
You can turn on the following options in SAS to assist with macro debugging and visualisation, check the SAS documentation for more info:
SYMBOLGEN
MLOGIC
MPRINT