Mastering SAS Nested Macro Variables and Ampersand Resolution
Mastering SAS Nested Macro Variables and Ampersand Resolution
Dynamic programming in SAS relies heavily on the SAS Macro Facility. While simple macro variables (like &var) are easy to use, things get interesting—and sometimes confusing—when we start nesting them. This post breaks down the rules of ampersand resolution so you can master indirect referencing in your SAS programs.
What is Indirect Referencing?
Indirect referencing occurs when the value of one macro variable is the name of another macro variable. To handle this, SAS uses multiple ampersands. The key to understanding how SAS processes these is to follow three fundamental rules.
The Three Golden Rules of Resolution
- Rule 1: Double Ampersands: Two ampersands (
&&) resolve to a single ampersand (&). - Rule 2: Left-to-Right Scanning: The macro processor scans the code from left to right.
- Rule 3: Recursive Re-scanning: After a pass, the processor re-scans the result if any ampersands remain, repeating the process until all references are resolved.
A Practical Example: &&var&i
Imagine you have a series of variables: var1, var2, and var3. You are using a loop where the macro variable &i changes from 1 to 3. How do you reference var1 using &i?
You write: &&var&i
Let’s trace the resolution for the first pass (where &i = 1):
- Scanning starts from the left: The processor sees
&&. - Rule 1 applied:
&&becomes&. - Next is “var”: This is literal text, so it stays
var. - Next is
&i: The processor resolves this to1. - End of first pass: The resulting string is
&var1. - Rule 3 applied: The processor re-scans
&var1. - Final Resolution: The processor resolves
&var1to its stored value (e.g., “Clinical Data”).
Why Use This?
Nested variables are essential for:
– Looping through datasets: Dynamically generating variable names within a %DO loop.
– Automation: Creating flexible code that adapts to changing data structures without manual hard-coding.
– Complex Lookups: Retrieving values from a “mapping” macro variable based on a dynamic key.
Summary
Mastering the “Macro World” requires a firm grasp of how ampersands behave. Remember: && is just an & in waiting, and the processor is persistent—it will keep scanning until the job is done!
This content is based on the SAS Course materials from the online course at made2sticklearning.org/sas

