SAS Macro Variables
Contents
Defining Variables
A macro variable can be defined like:
%let LABEL = VALUE;
A macro's value can be access like:
&LABEL
Using Macros
A macro definition can reference another macro. To use a SAS function in defining a macro variable, the %sysfunc macro function must be used.
%let mon = 1; %let curr_yr = %sysfunc(year("&sysdate"d)); %let mon_title = %sysfunc(mdy(&mon,1,&curr_yr), monname9.); %let mon_title = %sysfunc(left(%qsysfunc(mdy(&mon,1,&curr_yr), monname9.)));
For considerations on using macro functions including %sysfunc, see Macro Functions.
Defining Variables in the Data Step
A macro variable can be set by symputx calls, and retrieved by symget calls. This enables programmatic creation and use of macros, i.e. for aggregation of data.
data _NULL_; set LIBREF.TABLE end=lastobs; retain sum_sales 0; sum_sales = sum_sales + sales; if lastobs then call symputx('total_sales', put(sum_sales, dollar10.2)); run; data temp; set LIBREF.TABLE; total_sales = input(symget('total_sales'), dollar10.2); run;
Setting
symput and symputx both take two string arguments-the macro variable name and its value. In order to set a numeric value into the macro, it must be converted using put.
symput and symputx are very similar. The latter is silent and trims leading spaces, whereas the former will log information and preserve leading spaces. Generally, symputx is the right option.
Accessing
symget and symgetn take a single string argument-the macro variable name. The variable must be defined.
symget is for character data, while symgetn implicitly converts to numeric.
resolve works in a similar manner, but takes a macro label with the trigger prefix (& or %), and can be used to get the value of a macro variable or function. For more details, see below.
Defining Variables in the SQL Process
A macro variable can be set by PROC SQL. This has many of the same benefits as with the data step.
proc sql noprint; select sum(sales) format=dollar10.2 into :total_sales from LIBREF.TABLE; quit;
proc sql also sets three background macro variable.
SQLOBS is the number of rows produced with a SELECT statement
SQLRC is the return code from the ultimate statement
SQLOOPS is the number of iterations from the ultimate (i.e., highest-level) loop
See here for more details.
Scope
A macro variable defined by open code is stored in the global table. A macro variable defined in a separate program is local. By the nature of SAS, most custom macros will be global.
If necessary, it is possible to force local resolution of a label.
%local A; %let A=B;