Skip to content
AgileLogics
7 min read

Macro Variables

The SAS macro language writes SAS code for you. It runs before the code it generates — a text-substitution layer on top of SAS. Its simplest tool is the macro variable: a named piece of text.

%LET and &

%let min_age = 14;

title "Students aged &min_age or older";
proc print data=sashelp.class noobs;
   where age >= &min_age;
   var name age;
run;
title;
   Students aged 14 or older

Name       Age

Alfred      14
Carol       14
Henry       14
Janet       15
Judy        14
Mary        15
Philip      16
Ronald      15
William     15
  • %let name = value; stores text. There are no types — 14 is two characters. Leading and trailing blanks are dropped.
  • &min_age is replaced by its text before SAS sees the code.
  • Macro references resolve only inside double quotes. title 'Age &min_age'; prints &min_age literally.

Change the %let once, and every step that uses it follows.

Seeing values in the log

%let region = North;
%put Region is &region;
%put &=region;
Region is North
REGION=North

%put _user_; lists every macro variable you've created. SAS also defines automatic macro variables such as &sysdate9 (the date the session started), &sysuserid, and &syserr (the status of the last step).

Creating macro variables from data

CALL SYMPUTX in a DATA step and INTO : in PROC SQL store computed values:

data _null_;
   set sashelp.class end=last;
   total + weight;
   if last then call symputx('total_wt', total);
run;

proc sql noprint;
   select count(*) into :n_old trimmed
   from sashelp.class
   where age >= 14;
quit;

%put &=total_wt;
%put There are &n_old students aged 14 or older.;
TOTAL_WT=1900.5
There are 9 students aged 14 or older.
  • end=last sets last to 1 on the final row.
  • SYMPUTX converts numbers to text and trims blanks; trimmed does the same for INTO.
  • A macro variable created in a step can be used only in later steps, because macro references in a step resolve before the step runs.
  • select name into :names separated by ' ' builds a list of values.

Arithmetic and delimiters

%let a = 10;
%put %eval(&a / 3) %sysevalf(7 / 2);
%let lib = sashelp;
%put &lib..class;
3 3.5
sashelp.class
  • %EVAL does integer arithmetic; %SYSEVALF handles decimals.
  • A period ends a macro variable name, so &lib..class needs two: the first ends the reference, the second is the real dot.