100% found this document useful (3 votes)
9K views51 pages

SAS Slides 12: Macros

Learning Base SAS, Advanced SAS, Proc SQl, ODS, SAS in financial industry, Clinical trials, SAS Macros, SAS BI, SAS on Unix, SAS on Mainframe, SAS interview Questions and Answers, SAS Tips and Techniques, SAS Resources, SAS Certification questions... visit http://sastechies.blogspot.com

Uploaded by

SASTechies
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT or read online on Scribd
100% found this document useful (3 votes)
9K views51 pages

SAS Slides 12: Macros

Learning Base SAS, Advanced SAS, Proc SQl, ODS, SAS in financial industry, Clinical trials, SAS Macros, SAS BI, SAS on Unix, SAS on Mainframe, SAS interview Questions and Answers, SAS Tips and Techniques, SAS Resources, SAS Certification questions... visit http://sastechies.blogspot.com

Uploaded by

SASTechies
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT or read online on Scribd
You are on page 1/ 51

SAS Techies

info@sastechies.com
http://www.sastechies.com
 Creating
◦ SAS Tables,
◦ Listings,
◦ Basic Statistics Procedures with SAS
◦ Graphs TLG’s
◦ and ODS HTML
◦ Proc Report

 Advanced SAS Programming Concepts


◦ SAS Macros
◦ SQL Joins
◦ Match merging
◦ Arrays for Look up

SAS Techies 2009 11/02/21 2


 SAS macro variables
title "Temporary Employees for 1999"; enable you to substitute
data hrd.temp1999; text in your SAS
set hrd.temp; if year(enddate)=1999; programs.
 Macro variables can
title "Temporary Employees for 2000"; supply a variety of
data hrd.temp 2000; information, from
set hrd.temp; if year(enddate)= 2000; operating system
information to SAS
session information to
%let yr=1999; any text string you
title "Temporary Employees for &yr"; define.
data hrd.temp&yr;  By substituting text into
set hrd.temp; if year(enddate)= “&yr”; programs, SAS macro
variables make your
& % - Macro facility trigger telling SAS programs easy to update
to resolve the value immediately

SAS Techies 2009 11/02/21 3


 SAS Macro Variables SAS
macro variables are part of
the macro facility, which is
a tool for extending and
customizing SAS software
and for reducing the
amount of text you must
enter to complete tasks.
 A macro variable is
independent of a SAS data
set and contains one value
that remains constant until
you change it.
%let yr=1999;
title "Temporary Employees for &yr";  The value of a macro
data hrd.temp&yr; variable is always a text
set hrd.temp; if year(enddate)= &yr; string that becomes part of
your program whenever the
macro variable is
referenced.

SAS Techies 2009 11/02/21 4


types of macro variables:
footnote "Report Run on &sysdate"; ◦ automatic macro variables -
provided by SAS software
Obs Agency ID Name ◦ user-defined macro variables
1 Administrative Support, Inc. F274 Cichock, Elizabeth Marie – created by the users
2 OD Consulting, Inc. F054 Shere, Brian Thomas

If single quotes enclose a macro


3 Administrative Support, Inc. P039 Chevarley, Arlene Elsie
4 New Time Temps Agency P378 Bates, Ellen Marie
variable reference, it is not
resolved by SAS software.
Report Run on
30NOV99
Macro variable references that
footnote ‘Report Run on &sysdate’; appear in quoted strings must
be enclosed in double quotes.
footnote “Report Run on &sysdate”;
Macro Variables cannot be
defined with DATALINES

SAS Techies 2009 11/02/21 5


Automatic Macro Name Information Example
Variables SYSDATE9  date the job or session 21APR2000

◦ Whenever you invoke the began executing


SAS System, automatic
macro variables are
16FEB98
SYSDATE date the job or session
created that provide such began executing
information as the SYSDAY weekday the job or Tuesday

◦ date or time a SAS job or session began


session began executing
executing
◦ release of SAS software
you are running SYSTIME time the job or session 15:32

◦ name of the most began executing


recently created SAS data SYSSCP operating system CMS
set abbreviation
◦ abbreviation for your host
operating system.
7.0
SYSVER SAS software version
and/or release number
HRD.TEMP99
SYSLAST name of most recently
created data set
SAS Techies 2009 11/02/21 6
%let name=sharad;
title "Temporary Employees for &name";
data hrd.temp;
 Vimp-The quotes are
set hrd.temp; if name=&name; needed to correctly
%let name=sharad; assign the text string
title "Temporary Employees for Sharad";
data hrd.temp;
that is contained in
set hrd.temp; if name=sharad; the macro variable.
%let name=sharad;
 If NO quoted are
title "Temporary Employees for Sharad"; provided SAS looks
data hrd.temp;
set hrd.temp; if name=“&name”; for the value in the
%let name=sharad;
variable Sharad in the
title "Temporary Employees for Sharad"; Set dataset
data hrd.temp;
set hrd.temp; if name=“sharad”;

SAS Techies 2009 11/02/21 7


 %let region=northwest;  User-defined macro variables
 %let region='northwest'; enable you to substitute a
 %let level=768; wider range of text in your
 %let lev=&level; resolves to 768 programs because you can
 %let rate=700+700*.05; control the values of the
 %let region =North West ;
macro variables.
 %let region =‘North West ‘;
 %LET name=value;
 Everything appearing
between the equal sign and
semicolon is considered part
of the macro variable value.
 %let removes all leading and
trailing blank spaces by
default except when in
quotes;
 The use of the SYS prefix is
reserved to SAS software for
automatic macro variable
names.

SAS Techies 2009 11/02/21 8


 Whether automatic or user-  The value of a macro
defined, a macro variable is variable is stored in a
independent of a SAS data symbol table.
set and contains one text  The values of automatic
string value that remains macro variables are always
constant until you change stored in the global symbol
it. The value of a macro table, meaning that these
variable is substituted into values are always available
your program wherever the in your SAS session.
macro variable is  The values of user-defined
referenced. macro variables are often
stored in the global symbol
Global Symbol Table table as well.
SYSTIME 09.47 automatic
varia
 %let city=Dallas;
SYSVER 8.01 bles  %local Date=05JAN2000;
CITY Dallas user-
defin
 %global amount=975;
DATE 05JAN2000 ed
varia
AMOUNT 975 bles

SAS Techies 2009 11/02/21 9


 When you submit a program, it
goes to an area of memory
called the input stack. This is
true for all code that you submit,
such as a DATA step, SCL code,
or SQL code.
 Once SAS code is in the input
stack, SAS
◦ reads the text in the input
stack (left-to-right, top-to-
bottom)
◦ routes text to the appropriate
compiler upon demand
◦ suspends this activity when a
step boundary such as a RUN
statement is reached
◦ executes the compiled code if
there are no compilation
errors
◦ repeats this process for any
subsequent steps.

SAS Techies 2009 11/02/21 10


 The macro facility performs its tasks before
SAS programs execute, the information that
the macro facility supplies does not depend
on values that are accessed or computed
during the execution of a SAS program.

SAS Techies 2009 11/02/21 11


 Between the input stack and
the compiler, SAS programs
are tokenized into smaller
pieces.
 A component of SAS known
as the word scanner divides
program text into
fundamental units called
tokens.
◦ Tokens are passed on
demand to the compiler.
◦ The compiler requests
tokens until it receives a
semicolon.
 literal token - Eg: "Any text"  'Any text' ◦ The compiler performs a
 number token - Eg:
23  109  '01jan2002'd  5e8  42.7
syntax check on the
 name token - Eg:
statement.
infile  _n_  item3  univariate  dollar10.2
 special tokens - Eg:
* / +  -  **  ;  $  (  )  .  &  %

SAS Techies 2009 11/02/21 12


 Macro Triggers
◦ % followed immediately by a name
token (such as %let)
◦ & followed immediately by a name
token (such as &amt).

 When a macro trigger is detected, the


word scanner passes it to the macro
processor for evaluation.

 For macro variables, the processor


does one of the following:
◦ creates a macro variable in the
symbol table and assigns a value to
the variable
◦ changes the value of an existing
macro variable in the symbol table
◦ looks up an existing macro variable
in the symbol table and returns the
variable's value to the input stack in
place of the original reference.

SAS Techies 2009 11/02/21 13


SAS Techies 2009 11/02/21 14
SAS Techies 2009 11/02/21 15
SAS Techies 2009 11/02/21 16
SAS Techies 2009 11/02/21 17
%let name=sharad;
data hrd.&name;
option symbolgen;
data hrd.sharad; %let chakri=Narnindi;
%let sharad=chakri;
Suppose I want this %let name=sharad;
Data hrd.sharadnew %let cool=&&name;
%let new=&&&name;
data hrd.&namenew; %put _user_;
data hrd.&name.new

Data sharad.sasd
Data &name.sasd - Left – right Forward Scanning
sharadsasd rule
Where sharad is a libname && - &
Data &name..sasd -
sharad.sasd

SAS Techies 2009 11/02/21 18


 OPTIONS NOSYMBOLGEN  SYMBOLGEN specifies
| SYMBOLGEN; that log messages will be
displayed.
 a message is displayed
for each resolved macro
%let year=1999; variable reference.
title "Temporary Employees for &year";  When SAS software
data hrd.newtemp; encounters a macro
set hrd.temp; if year(enddate)=&yera; run; variable reference but
cannot locate a macro
title "Temporary Employees for &year"; variable by that name,
data hrd.newtemp; the reference is left
set hrd.temp; if year(enddate)=&year; run; unresolved and a
warning message is
generated

SAS Techies 2009 11/02/21 19


 General form, basic %PUT  The %PUT statement
statement: ◦ writes only to the SAS log
◦ %PUT text; - where text is any
text string. ◦ always writes to a new log
line, starting in column one
◦ writes a blank line if text is
not specified
Argument Result in SAS Log
◦ does not require quotation
_ALL_ Lists the values of all macro variables marks around text
_AUTOMATIC_ Lists the values of all automatic macro variables ◦ resolves macro triggers in
_USER_ Lists the values of all user-defined macro variables text before text is written
◦ removes leading and trailing
blanks from text unless a
macro quoting function is
used
◦ wraps lines when the length
of text is greater than the
current line size setting
◦ can be used either inside or
outside a macro definition.  

SAS Techies 2009 11/02/21 20


%let prog=data new; x=1; run;  The %STR function is used to mask
&prog     (or quote) tokens so that the
macro processor does not interpret
proc print; them as macro-level syntax.
 Method One: You could quote all  They can be used to mask-
text.
     ; + - * / , < > = blank LT  EQ 
%let prog=%str(data new; x=1; run;);
 Method Two: You could quote only GT  AND  OR  NOT  LE  GE  NE
the semicolons.
%let prog=data new The %STR function also
%str(;)x=1%str(;)run%str(;); ◦ enables macro triggers to work
 Method Three: You could create an normally
additional macro variable, assign a ◦ preserves leading and trailing
quoted value to it, and reference it blanks in its argument.
in the assignment statement for
the prog macro variable.
 The %STR function can also be
%let s=%str(;);     %let prog=data used to quote tokens that typically
new&s x=1&s run&s; occur in pairs:
    %let text=%str(Joan%'s Report);     ' "  ) (
%let text=Joan%str(%')s Report;

SAS Techies 2009 11/02/21 21


%let Period=%str(May&Jun);  Sometimes you might
    %put Period resolves to: &period;  
want to hide the normal
 
%let Period=%nrstr(May&Jun);
meaning of an
    %put Period resolves to: &period; ampersand or a percent
sign.

 The %NRSTR function


performs the same
quoting function as
%STR, except it also
masks macro triggers (&
and %).

SAS Techies 2009 11/02/21 22


 %upcase  %qupcase
where paid="%upcase(&paidval)";  %QSUBSTR
 %QSCAN Function
 %SUBSTR   %QSYSFUNC
%substr(&date,3)

 %SCAN
%scan(&c,1,*);

 %SYSFUNC
%sysfunc(today(),weekdate.)

 %INDEX

 %LENGTH

SAS Techies 2009 11/02/21 23


 Because the macro facility  In many applications, you
performs its tasks before need to create macro
SAS programs execute, the variables during DATA step
information that the macro execution. You might need
facility supplies does not to create macro variables
depend on values that are and to assign values to
accessed or computed them based on
during the execution of a ◦ data values in SAS data sets
SAS program. or in external files
◦ programming logic
◦ computed values.

  The DATA step provides


functions and CALL
routines that enable you to
transfer information
between an executing
DATA step and the macro
processor.

SAS Techies 2009 11/02/21 24


data hrd.overtime;  if you need a macro variable to
set hrd.temp(keep=name overtime); contain a value that is created
if overtime ne .; during the execution of the
DATA step, the %LET statement
TotalOvertime+overtime; cannot define this macro
run; variable.
title "Temporary Employees Worked CALL SYMPUT( name,value);
&total OT Hours"; ◦ name is the name of the macro
proc print data=hrd.overtime; run; variable to be defined. The
variable can be a character string
enclosed in quotes, a character
data hrd.overtime; variable, or a character
set hrd.temp(keep=name overtime); expression.
if overtime ne .; ◦ value is the value to be assigned
to the macro variable. The value
TotalOvertime+overtime; can be a text string enclosed in
call symput('total',totalovertime); quotes, a data set variable, or a
DATA step expression.
run;
title "Temporary Employees Worked Most often used pulling data with
Views……
&total OT Hours";
proc print data=hrd.overtime; run;

SAS Techies 2009 11/02/21 25


 When you use the SYMPUT
routine to create a macro
variable in a DATA step, the
data hrd.overtime; set hrd.temp(keep=name macro variable is not actually
overtime); created and assigned a value
if overtime ne .;
until the DATA step is
executed. Therefore, you
TotalOvertime+overtime; cannot successfully reference a
call symput('total',put(totalovertime,2.)); macro variable that is created
run; with the SYMPUT routine by
preceding its name with an
ampersand within the same
title "Temporary Employees Worked &total OT DATA step in which it is
Hours"; created.
proc print data=hrd.overtime;
run;  When converting numeric to
character remember every
numeric value is in the BEST12.
format.
 Take care of it by using
formats, trim(left())
combinations, scan,
substr,compress functions

SAS Techies 2009 11/02/21 26


 Using SYMPUT with a Literal  When you use a DATA step
CALL SYMPUT('macro-variable','text'); expression as the second
argument, its current value is
 Using SYMPUT with a DATA Step evaluated according to the
Variable following rules:
CALL SYMPUT('macro-variable',DATA-step-
variable);
 Numeric expressions are
automatically converted to
 Using CALL SYMPUT with DATA
character constants, using the
Step Expressions BEST12. format.
       call symput('due',
 The resulting value can be up to
trim(left(put(fee*(total- 32767 characters long.
paidup),dollar8.))));  Any leading or trailing blanks
that are part of the expression
 Creating Multiple Macro Variables are stored in the macro variable.
with CALL SYMPUT
       call symput(course_code,
trim(course_title));
       call symput('teach'||
left(course_number),                   
trim(teacher));

SAS Techies 2009 11/02/21 27


 The INTO clause in a SELECT ◦ the INTO clause cannot be used
statement enables you to create when you create a table or a
or update macro variables. view.

proc sql NOPRINT;     ◦ Most common usage -


select course_code, location, begin_date select count(*) into :numrows
format=mmddyy10.       
into :crsid1-:crsid3,
       :place1-:place3, select course_code,
      :date1-:date3 location,
from sasuser.schedule begin_date format=mmddyy10.
where year(begin_date)=2002   into :crsid1-:crsid&numrows,  
order by begin_date;     quit;
         :place1-:place&numrows

◦ SELECT column1 INTO :macro-


variable-1 SEPARATED BY
'delimiter1'

SAS Techies 2009 11/02/21 28


%let crsid=C003;    
 SYMGET(‘macro-variable’)

proc sql;
Global Symbol Table create view subcrsid as
TEACH1 Hallis, Dr. George select
TEACH2 Wickam, Dr. Alice student_name,student_company,p
TEACH3 Forest, Mr. Peter
aid
CRS 3
From sasuser.all
where course_code=symget('crsid');
    quit;
       teacher=symget('teach'||left(course_number));

SAS Techies 2009 11/02/21 29


%MACRO macro-name;  After the macro is successfully
text compiled, you can use it in your
%MEND <macro-name>; SAS programs for the duration of
your SAS session without
resubmitting the macro
where definition. Just as you must
 macro-name names the macro. reference macro variables in
 The value of macro-name can be order to access them in your
code, you must call a macro
any valid SAS name that is not a program in order to execute it
reserved word in the SAS macro within your SAS program.
facility.
 text can be
◦ constant text, possibly including
 A macro call
SAS data set names, SAS variable ◦ is specified by placing a percent
names, or SAS statements sign (%) before the name of the
◦ macro variables, macro functions, macro
or macro program statements ◦ can be made anywhere in a
◦ any combination of the above. program except within the data
lines of a DATALINES statement
(similar to a macro variable
reference)
◦ requires no semicolon because it
is not a SAS statement.

SAS Techies 2009 11/02/21 30


 When you call a macro in your SAS program, the word
scanner passes the macro call to the macro processor,
because the percent sign that precedes the macro name is
a macro trigger.

When the macro processor receives %macro-name, it


◦ searches the designated SAS catalog (Work.Sasmacr by
default) for an entry named Macro-name.Macro.
◦ executes compiled macro language statements within
Macro-name.
◦ sends any remaining text in Macro-name to the input stack
for word scanning.
◦ suspends macro execution when the SAS compiler receives
a global SAS statement or when it encounters a SAS step
boundary.
◦ resumes execution of macro language statements after the
SAS code executes.

SAS Techies 2009 11/02/21 31


 Symbolgen option – Macros resolved values
 The MPRINT option - the text that is sent to the SAS compiler
as a result of macro execution is printed in the SAS log.
 The MLOGIC Option –

When the MLOGIC system option is in effect, the information


that is displayed in SAS log messages includes
◦ the beginning of macro execution
◦ the results of arithmetic and logical macro operations
◦ the end of macro execution.

 All these options are used in Code Development phase and


turned off in Production/Testing Phases….Required….display
passwords….extraneous log files…

SAS Techies 2009 11/02/21 32


%macro prtlast;   
proc print
data=&syslast(obs=5);  
title "Listing of &syslast data
set";   
run;
%mend;
   
data sales;
price_code=1;    
run;
options mprint;    
%prtlast

SAS Techies 2009 11/02/21 33


%macro printdsn(dsn,vars);  When you include positional
     proc print data=&dsn; parameters in a macro
      var &vars; definition, a local macro
variable is automatically
      title "Listing of created for each parameter
%upcase(&dsn) data set";          when you call the macro.
run;     
%mend;  To define macros that include
positional parameters, you list
the names of macro variables
To substitute a null value for in the %MACRO statement of
the macro definition.

one or more positional
parameters, use commas as
placeholders for the omitted  Positional parameters are so
values, as follows: named because the order in
which you specify them in a
%printdsn(,course_code macro definition determines
course_title days) the order in which they are
assigned values from the
macro call.

SAS Techies 2009 11/02/21 34


 when you use keyword
%macro printdsn(dsn= parameters to create macro
sasuser.courses,vars=course_code variables, you list both the
                    course_title days); name and the value of each
  proc print data=&dsn;   macro variable in the macro
   var &vars; definition.
  title "Listing of %upcase(&dsn) data
set";  When you call a macro
  run;      whose definition includes
%mend; keyword parameters, you
%printdsn(dsn=sasuser.schedule, specify both the keyword
vars=teacher               course_code
begin_date) and the value for each
parameter, in any order. If
you omit a keyword
parameter from the macro
call, the keyword variable
retains its default value

SAS Techies 2009 11/02/21 35


 when you call a macro
%macro printdsn(dsn, that includes a mixed
vars=course_title parameter list, you must
course_code days); list the positional values
proc print data=&dsn;   before any keyword
var &vars; values, as follows:
title "Listing of %upcase(&dsn)
data set";
%macro-name(value-
run; 1<,...,value-n>,
%mend;                 keyword-
1=value-1<,...,keyword-
n=value-n>)

SAS Techies 2009 11/02/21 36


%macro printz/parmbuff;    Parmbuff option allows to
%put Syspbuff contains: &syspbuff; send varying parameter
  %let num=1;  
  %let dsname=
calls to macros.
%scan(&syspbuff,&num,’,’);  The automatic macro
variable SYSPBUFF is used
%do %while(&dsname ne _ ); to capture those variable
proc print data=sasuser.&dsname; values.display the
run;
parameters that are
%let num=%eval(&num+1); specified in the macro call.
%let dsname=
%scan(&syspbuff,&num,’,’);
%end;     
%mend printz;

%printz (dsn1,dsn2, dsn3)

SAS Techies 2009 11/02/21 37


 You can create a global macro  automatic macro variables are
variable with stored in the global symbol
◦ a %LET statement (used outside a table. User-defined macro
macro definition) variables that you create with a
◦ a DATA step that contains a %LET statement in open code
SYMPUT routine (code that is outside of a macro
◦ a SELECT statement that contains definition) are also stored in the
an INTO clause in PROC SQL global symbol table.
◦ a %GLOBAL statement.
 The global symbol table is
created during the initialization
of a SAS session and is deleted
at the end of the session. Macro
variables in the global symbol
table
◦ are available anytime during the
session
◦ can be created by a user
◦ have values that can be changed
during the session (except for
some automatic macro variables).

SAS Techies 2009 11/02/21 38


 You can create local macro  A local symbol table is created
variables with - when a macro that includes a
◦ parameters in a macro definition parameter list is called or when a
◦ a %LET statement within a macro request is made to create a local
definition variable during macro execution.
◦ a DATA step that contains a
SYMPUT routine within a macro  The local symbol table is deleted
definition
◦ a SELECT statement that contains when the macro finishes
an INTO clause in PROC SQL within execution.
a macro definition
◦ a %LOCAL statement.  That is, the local symbol table
exists only while the macro
executes.
 The local symbol table contains
macro variables that can be
◦ created and initialized at macro
invocation (that is, by parameters)
◦ created or updated during macro
execution
◦ referenced anywhere within the
macro.

SAS Techies 2009 11/02/21 39


%let dsn=sasuser.courses;      
%macro printdsn;   
     %local dsn;   
     %let dsn=sasuser.register;
       %put The value of DSN inside Printdsn is &dsn;
    %mend;  
    %printdsn    
%put The value of DSN outside Printdsn is &dsn;

SAS Techies 2009 11/02/21 40


%macro outer;    Multiple local symbol tables
   %local variX; can exist concurrently during
    %let variX=one; macro execution if you have
     %inner    
nested macros.
%mend outer;  That is, if you define a macro
program that calls another
    %macro inner; macro program, and if both
      %local variY; macros create local symbol
       %let variY=&variX;   tables, then two local symbol
   %mend inner; tables will exist while the
second macro executes.
%let variX=zero;   
%outer
 When a macro finishes
executing, its local symbol
table and all of the local macro
variables that are contained in
that table are erased. The
global symbol table and all of
the global macro variables that
are contained in it remain.

SAS Techies 2009 11/02/21 41


Yes

Update macvar in the local


Does macvar already exist in the local
symbol table with the value
symbol table?
value.

No  
Yes

Update macvar in the global


Does macvar already exist in the
symbol table with the value
global symbol table?
value.

No  

Create macvar in the local symbol


 
table and assign a value of value to it.

SAS Techies 2009 11/02/21 42


Yes

Retrieve the value of


Does macvar exist in the local symbol table? macvar from the local
symbol table.

No  
Yes

Retrieve the value of


Does macvar exist in the global symbol table? macvar from the
global symbol table.

No  

Return the tokens to the word scanner. Issue a


warning message to the SAS log to indicate that the  
reference was not resolved.

SAS Techies 2009 11/02/21 43


 If expression resolves to zero,
then it is false and the %THEN
text is not processed (the
optional %ELSE text is processed
instead). %IF-%THEN... IF-THEN...
%macro choice(status);
data fees;
set sasuser.all; is used only in a macro is used only in a DATA step
program. program.
%if &status=PAID %then %do;
       where paid='Y';
       keep student_name
course_code begin_date totalfee;
       %end;    executes during macro executes during DATA step
%else %do; execution. execution.
        where paid='N';
       keep student_name
course_code
       begin_date totalfee latechg;   uses macro variables in uses DATA step variables in
       latechg=fee*.10;    logical expressions logical expressions.
        %end; and cannot refer to
Run; DATA step variables in
%mend choice; logical expressions.
%choice(PAID); determines what text determines what DATA step
should be copied to statement(s) should be
the input stack. executed. When inside
a macro definition, it is
copied to the input
stack as text.

SAS Techies 2009 11/02/21 44


data _null_;  With the iterative %DO
set sasuser.schedule statement you can repeatedly
end=no_more; ◦ execute macro programming
call symput('teach'||left(_n_), code
(trim(teacher)));        ◦ generate SAS code.
if no_more then call
symput('count',_n_);  %DO and %END statements are
run; valid only inside a macro
definition
%macro putloop;
     %local i;
       %do i=1 %to &count;
          %put TEACH&i is &&teach&i;
       %end;
%mend putloop;

%putloop

SAS Techies 2009 11/02/21 45


 The %EVAL function  The %EVAL function does not
◦ translates integer strings convert the following to numeric
and hexadecimal strings to values:
integers. ◦ numeric strings that contain a
period or E-notation
◦ translates tokens ◦ SAS date and time constants.
representing arithmetic,
comparison, and logical
operators to macro-level  The %SYSEVALF function
operators. performs floating-point
◦ performs arithmetic and arithmetic and returns a value
that is formatted using the
logical operations. BEST32. format. The result of the
evaluation is always text.
 For arithmetic expressions, if
an operation results in a non-
integer value, %EVAL truncates
the value to an integer. Also,
%EVAL returns a null value and
issues an error message when
non-integer values are used in
arithmetic expressions.

SAS Techies 2009 11/02/21 46


 use the %INCLUDE statement to
Code - c:\sasfiles\prtlast.sas insert the statements that are
   %macro prtlast; stored in the external file into a
program.
    %if &syslast ne _NULL_ %then %do;
      proc print data=&syslast(obs=5);  
      title "Listing of &syslast data set";
 By storing your macro program
      run;       
externally and using the
%INCLUDE statement, you gain
%end; several advantages over using
    %else session-compiled macros.
   %put No data set has been created ◦ The source code for the macro
yet.; definition does not need to be
    %mend; part of your program.
◦ A single copy of a macro
Your Program definition can be shared by
%include 'c:\sasfiles\prtlast.sas' many programs.
/source2; ◦ Macro definitions in external
proc sort data=sasuser.courses files are easily viewed and
out=bydays; edited with any text editor.
by days; ◦ No special SAS system options
run; are required in order to access
%prtlast a macro definition that is
stored in an external file.

SAS Techies 2009 11/02/21 47


OPTIONS MAUTOSOURCE |  You can make macros
NOMAUTOSOURCE; accessible to your SAS session
or program by using the
OPTIONS SASAUTOS=(library- autocall facility to search
1,...,library-n); predefined source libraries for
macro definitions known as
autocall libraries.
Eg:  When you submit a call to that
Libname sasmacs macro,
“'c:\mysasfiles'”; ◦ the macro processor searches
options mautosource the autocall library for the
sasautos=(sasmacs,sasautos); macro
    ◦ the macro is compiled and
stored as it would be if you had
submitted it (that is, the
%prtlast compiled macro is stored in the
default location of
Work.Sasmacr)
◦ the macro is executed.

SAS Techies 2009 11/02/21 48


 when a macro is compiled, it is
stored in the temporary SAS catalog
Work.Sasmacr by default. You can
OPTIONS MSTORED | NOMSTORED; also store compiled macros in a
permanent SAS catalog to use the
OPTIONS SASMSTORE=libref; Stored Compiled Macro Facility to
access permanent SAS catalogs that
%MACRO macro-name <(parameter-
contain compiled macros.
list)> /STORE
<DES='description'>;  There are several restrictions on
text stored compiled macros.
%MEND <macro-name>; ◦ Sasmacr is the only catalog in
which compiled macros can be
stored. You can create a catalog
named Sasmacr in any SAS library.
You should not rename this
catalog or its entries.
◦ You cannot copy stored compiled
macros across operating systems.
You must copy the source
program and re-create the stored
compiled macro.
◦ The source cannot be re-created
from the compiled macro. So save
the original source program.

SAS Techies 2009 11/02/21 49


SAS Techies 2009 11/02/21 50
 The %SYMDEL statement enables you to delete a macro variable from
the global symbol table during a SAS session.

 You can call a macro within a macro definition. That is, you can nest
macros.

 When a nested macro is called, multiple local symbol tables can


exist.

 The MPRINTNEST and MLOGICNEST options provide nesting


information in the messages that are written to the SAS log for the
MPRINT and MLOGIC options.

 You cannot nest functions within %SYSFUNC, but you can use a
%SYSFUNC for each function that you need, as shown in this
eg: title "Report Produced on %sysfunc(left(%sysfunc
put(today(),worddate.)))";

SAS Techies 2009 11/02/21 51

You might also like