Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Macros

Conditional Logic and Loops in Macros

Use %IF %THEN %ELSE, %DO, %DO %WHILE and %DO %UNTIL in SAS macros to generate repeated code, loop over lists, process many data sets, and know when to use DATA step logic instead.

Macro logic decides what code to write; DATA step logic decides what to do with each row. The macro statements %if and %do let a macro program generate different code depending on its parameters, or repeat a block of code for a list of data sets, years or variables. Mixing the two kinds of logic up is the number one confusion in macro programming, so we start there.

SAS cannot run on this site. The sas blocks are read-only. The TryIt blocks are Python stand-ins that generate the same program text a macro would, so you can read the generated SAS code.

Macro %IF is not DATA step IF

SAS
%macro show(ds, limit=);
  proc print data=&ds;
    %if &limit ne %then %do;
      where amount > &limit;
    %end;
  run;
%mend;

Here %if is evaluated while the macro is expanding, before SAS compiles anything. If limit is empty, the where statement is never written. In contrast, a normal if amount > 100 then ... in a DATA step is evaluated for every row at run time. The macro %if can only see macro variables and text, never data set values, and it can conditionally generate whole statements, even whole steps, which the DATA step if cannot.

Rules for %if:

  • Syntax: %if condition %then action; %else action;. For more than one statement use %do; ... %end;.
  • Comparisons are text comparisons unless both sides are integers, in which case they are numeric: %if &year > 2020 %then ... works numerically.
  • Use ne, eq, and, or, not and in. Do not put quotes around text for the comparison: %if &region = East %then.
  • %if is only allowed inside a macro (in older SAS releases; recent releases allow it at open code, but writing it inside a macro stays the portable style).

Stand-in: generating code conditionally

Python Stand-in: %IF decides what code is written

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Both outputs are valid SAS programs. The decision happened before SAS ever saw the code, which is exactly how %if works.

The iterative %DO loop

SAS
%macro yearly(first, last);
  %do y = &first %to &last;
    proc means data=work.sales_&y mean sum;
      var amount;
      title "Sales &y";
    run;
  %end;
%mend;

%yearly(2023, 2025)

The loop variable y is a macro variable. The loop writes three complete PROC MEANS steps, one for work.sales_2023, work.sales_2024 and work.sales_2025. Forms:

SAS
%do i = 1 %to 10 %by 2;   /* step size */
%do %while (&n < 5);      /* test first */
%do %until (&n >= 5);     /* test after the first pass */

%do %while and %do %until must change the condition inside the loop (for example %let n = %eval(&n + 1);), otherwise they never stop. Declare the loop variable with %local i; so a nested macro cannot corrupt it.

Looping over a list

A common need is "do this for each data set in a list". Store the list in a macro variable and walk through it with %scan:

SAS
%macro each(list);
  %local i item;
  %do i = 1 %to %sysfunc(countw(&list));
    %let item = %scan(&list, &i);
    proc contents data=work.&item short;
    run;
  %end;
%mend;

%each(sales costs returns)

countw counts words (spaces are the default separator), and %scan(&list, &i) picks word number i. The macro writes one PROC CONTENTS per item. When lists are built from data, the &&name&i pattern is also common: &&year&i resolves &i first to get &year1, then resolves &year1 to its value. (Recall Macro Variables for the two-pass rule.)

Stand-in: a macro loop over a list

Python Stand-in: %DO over a list with %SCAN

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Macros that call data

Macro logic cannot read data directly, but you can pass data into macro variables first and branch on them. A typical pattern is "only run the report if there are rows":

SAS
proc sql noprint;
  select count(*) into :nrows trimmed from work.exceptions;
quit;

%macro maybe_report;
  %if &nrows > 0 %then %do;
    proc print data=work.exceptions;
      title "&nrows exceptions found";
    run;
  %end;
  %else %do;
    %put NOTE: no exceptions, nothing to print.;
  %end;
%mend;

%maybe_report

Note the order: PROC SQL assigns nrows at run time of the SQL step, before the macro is called, so the macro can use it.

When not to use macro logic

Macro loops that call a DATA step once per observation are slow and hard to read. If you want to repeat work per row, use do loops, arrays and by-group processing in a DATA step. If you want to apply one operation to many columns, an array is simpler than a %do loop. Use macro loops to repeat steps (data sets, files, years, parameters), not rows.

Stand-in: a safe %DO %WHILE

Python Stand-in: loop with a changing condition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Remove the n = n + 1 line and the loop would never end. SAS has the same problem, and you stop a runaway macro by cancelling the submission.

Common mistakes

  1. Using %if to test a column (macro logic cannot see rows).
  2. Writing %if &x = 'a' with quotes, which compares the quoted text; leave the quotes off.
  3. Forgetting %end or %mend: the log shows A dangling %DO or the macro never closes.
  4. Forgetting %local for the loop variable.
  5. Putting a semicolon after a macro call inside the generated code, adding an extra empty statement.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When is a macro %IF evaluated?

    The macro processor evaluates %IF during expansion; it can see only macro variables and text.
  2. 2. What does %do y = 2023 %to 2025; ... %end; do?

    The iterative %DO repeats the generation of code with a macro loop variable.
  3. 3. What must a %DO %WHILE loop contain to avoid running forever?

    Unless something inside the loop changes the tested value, the condition never becomes false.
  4. 4. Which function picks the Nth word of a macro list?

    %scan(&list, n) returns the nth word; %sysfunc(countw(&list)) counts them.

Summary

  • Macro %if and %do decide what code is generated; DATA step if and do act on rows.
  • %if ... %then %do; ... %end; %else %do; ... %end; shapes code from parameters.
  • %do i = a %to b %by c, %do %while and %do %until repeat code generation.
  • Loop over lists with %scan and %sysfunc(countw()); resolve indirect names with &&name&i.
  • Use macros to repeat steps, not rows; declare loop variables with %local.

Next: PROC SQL: SELECT Basics