Macros enable you to substitute text
in a program and to do many other things. A SAS program can contain
any number of macros, and you can invoke a macro any number of times
in a single program.
To help you learn how
to define your own macros, this section presents a few examples that
you can model your own macros after. Each of these examples is fairly
simple; by mixing and matching the various techniques, you can create
advanced, flexible macros that are capable of performing complex tasks.
Each macro
that you define has a distinct name. When choosing a name for your
macro, it is recommended that you avoid a name that is a SAS language
keyword or call routine name. The name that you choose is subject
to the standard SAS naming conventions. (See the Base SAS language
documentation for more information about SAS naming conventions.)
A macro definition is placed between a %MACRO statement and a %MEND
(macro end) statement, as in the following example:
%MACRO macro-name;
%MEND macro-name;
The
macro-name specified in the %MEND statement must
match the
macro-name specified
in the %MACRO statement.
Note: While specifying the
macro-name in the %MEND statement is not required,
it is recommended. It makes matching %MACRO and %MEND statements while
debugging easier.
Here is an example of
a simple macro definition:
%macro dsn;
Newdata
%mend dsn;
This macro
is named DSN.
Newdata
is the text of the
macro. A string inside a macro is called
constant text or
model text because it is the model,
or pattern, for the text that becomes part of your SAS program.
To call (or
invoke) a macro, precede the name of the macro with
a percent sign (%):
Although the call to
the macro looks somewhat like a SAS statement, it does not have to
end in a semicolon.
For example, here is
how you might call the DSN macro:
title "Display of Data Set %dsn";
The macro processor
executes the macro DSN, which substitutes the constant text in the
macro into the TITLE statement:
title "Display of Data Set Newdata";
Note: The title is enclosed in
double quotation marks. In quoted strings in open code, the macro
processor resolves macro invocations within double quotation marks
but not within single quotation marks.
The macro DSN is exactly
the same as the following coding:
%let dsn=Newdata;
title "Display of Data Set &dsn";
The following code is
the result:
title "Display of Data Set Newdata";
So, in this case, the
macro approach does not have any advantages over the macro variable
approach. However, DSN is an extremely simple macro. As you will see
in later examples, macros can do much more than the macro DSN does.