SAS Macro Examples: 10 Practical Tips for Efficient SAS Programming
SAS macro examples are the fastest way to move from repetitive DATA steps and PROC calls to reusable, parameter-driven programs. Whether you are cleaning monthly sales data, generating dozens of reports, or standardizing clinical outputs, the SAS macro facility lets you package logic once and execute it many times with different inputs.
This guide walks through practical SAS macro examples that you can adapt immediately. We will cover simple macros, macro variables, %DO loops, %IF conditions, parameterized programs, dynamic titles, and debugging techniques that keep your code transparent and maintainable.
Core SAS Macro Examples Every Programmer Should Know
The foundation of the SAS macro language is surprisingly small: you define a macro, you call it, and you reuse it. Most production SAS jobs rely on this simple pattern because it reduces copy-and-paste errors and makes changes easier to deploy across many programs.
Before moving into advanced techniques, focus on the building blocks. A clear understanding of %MACRO, %MEND, %LET, and macro variable resolution will make every later SAS macro example easier to read and troubleshoot.
Creating a Basic Macro with %MACRO and %MEND
A basic macro wraps a block of SAS code between %MACRO and %MEND. You give the macro a name, then call it later with a percent sign. For example, you might create a macro that runs PROC MEANS on a specified data set and variable, then reuse it for different variables without rewriting the PROC step.
Here is a simple SAS macro example: %macro summary(data=, var=); proc means data=&data n mean std; var &var; run; %mend summary; After compiling this macro, you can call %summary(data=sashelp.cars, var=mpg_city) or %summary(data=sashelp.cars, var=invoice). The same logic runs twice with different inputs, which is the core benefit of macro programming.
Using %LET and Macro Variables in SAS Code
Macro variables store text that SAS resolves before executing the underlying code. The %LET statement is the simplest way to create them. For example, %let report_month=Jan2024; creates a macro variable named report_month that can be referenced later as &report_month inside a title, a filter, or a data set name.
A practical SAS macro example is filtering a data set by a dynamic month: data jan_sales; set all_sales; where month = "&report_month"; run; If the reporting period changes, you edit only the %LET statement instead of searching through dozens of WHERE clauses. This small change dramatically reduces maintenance time and prevents inconsistent hard-coded values across a project.
Dynamic SAS Macro Examples with Loops and Conditions
Once you can define macros and macro variables, the next step is adding logic. The macro language supports iterative %DO loops and conditional %IF-%THEN-%ELSE statements, allowing you to generate code dynamically based on parameter values or data-driven conditions.
These dynamic SAS macro examples are especially useful for producing repetitive reports, processing multiple years of data, or applying different business rules to different regions. The key is to keep the generated code readable and to document what the macro expects as input.
Building Iterative Reports with %DO Loops
A %DO loop repeats a block of macro code a specified number of times. You might use it to generate separate reports for each month, each product category, or each region. For example, %macro monthly_reports; %do m=1 %to 12; proc print data=sales_&m; title "Month &m"; run; %end; %mend; creates twelve PROC PRINT steps from one compact definition.
Another common SAS macro example uses a %DO loop over a list of values: %macro region_reports; %do %while(®ion ne ); ... %end; or %do i=1 %to %sysfunc(countw(®ion_list)); to iterate through a space-separated list. This pattern is ideal when the number of outputs is not fixed in advance and you want the macro to adapt to the data or configuration.
Applying Business Rules with %IF-%THEN-%ELSE
Macro %IF statements evaluate conditions at compile time, before the generated SAS code runs. This means you can include or exclude entire steps depending on a parameter. For instance, a macro might run a detailed report only when &detail=Y, otherwise it produces a summary table.
A realistic SAS macro example is adjusting statistical tests based on a user choice: %if &test=ttest %then %do; proc ttest data=analysis; class group; var outcome; run; %end; %else %if &test=anova %then %do; proc glm data=analysis; class group; model outcome=group; run; %end; This keeps one macro flexible enough to handle multiple analytical requests without duplicating the surrounding data preparation code.
Parameter-Driven SAS Macro Examples for Data Tasks
Parameter-driven macros are the workhorses of production SAS environments. Instead of editing code each month, you pass different values to the same macro. This approach improves consistency, reduces validation effort, and makes it easier to hand off programs between team members.
Good parameter design also makes your SAS macro examples easier to test. When each input is explicit, you can run small test cases and confirm that the macro behaves correctly before applying it to full production data.
Passing Parameters to Reusable Programs
A parameter can be positional or keyword-based. Keyword parameters are often clearer in production code because the call documents itself. For example, %macro extract(year=, state=, out=); clearly shows that the macro expects a year, a state, and an output data set name.
Suppose you need to extract sales data for many states. You could write %extract(year=2024, state=CA, out=ca_sales); and later %extract(year=2024, state=NY, out=ny_sales);. The macro might contain a WHERE clause like where year=&year and state="&state"; and a DATA step that writes to &out. This is one of the most common SAS macro examples in reporting and analytics teams.
Generating Dynamic Titles and Footnotes
Titles and footnotes are easy to overlook, but they are a frequent source of manual rework. With macro variables, you can build titles that update automatically. For example, title "Sales Report for &state - &year"; changes every time the macro is called with new parameters.
You can also use macro functions to format dates and labels. A useful SAS macro example is %let run_date=%sysfunc(today(), worddate.); title "Report Generated on &run_date"; This ensures every output carries an accurate generation date without manual editing. Footnotes can follow the same pattern, perhaps adding a data source or confidentiality note driven by a macro parameter.
Debugging and Improving SAS Macro Examples
Macro code can feel opaque when it does not work as expected because SAS resolves macro variables and generates code before execution. Fortunately, SAS provides powerful debugging options that show exactly what the macro is doing and what code it produces.
Adopting a few debugging habits early will save hours later. You will also write cleaner SAS macro examples because you will see how small changes in quoting, parameter defaults, or %IF logic affect the final generated program.
Using %PUT and MPRINT for Visibility
The %PUT statement writes messages to the SAS log. You can use it to display macro variable values, confirm which branch of an %IF statement executed, or print a checkpoint message. For example, %put NOTE: Processing state=&state year=&year; quickly reveals whether the expected values arrived inside the macro.
For deeper inspection, enable options mprint symbolgen; before calling the macro. MPRINT shows the SAS code generated by the macro, while SYMBOLGEN shows how macro variables resolve. Together they turn a silent failure into a readable trace, making even complex SAS macro examples easier to diagnose.
Best Practices to Avoid Macro Errors
Always use local macro variables inside macros unless you intentionally need global scope. A %local statement prevents a macro from accidentally overwriting a macro variable used elsewhere in the session. This simple practice avoids many hard-to-find bugs in large SAS programs.
Also, validate parameter values before using them. You can check for missing values with %if %superq(param)= %then %do; %put ERROR: param is required; %abort; %end; and use quoting functions like %superq or %bquote when parameters contain special characters. Clear error messages and defensive checks make your SAS macro examples more robust and easier for others to reuse.
The best way to internalize these SAS macro examples is to take one repetitive task from your current workflow and convert it into a small, parameter-driven macro. Start with a single PROC step, add one macro variable, then introduce a %DO loop or %IF condition as your confidence grows. Over time, that incremental practice will transform the way you write SAS code, making your programs shorter, smarter, and far easier to maintain.