Está en la página 1de 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/13/09 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 define.
title "Temporary Employees for &yr";  By substituting text into
data hrd.temp&yr; programs, SAS macro
set hrd.temp; if year(enddate)= “&yr”; variables make your
programs easy to update
& % - Macro facility trigger telling SAS
to resolve the value immediately

SAS Techies 2009 11/13/09 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
variable is always a text
data hrd.temp&yr; string that becomes part of
set hrd.temp; if year(enddate)= &yr; your program whenever the
macro variable is
referenced.

SAS Techies 2009 11/13/09 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 –
created by the users
1Administrative Support, Inc. F274 Cichock, Elizabeth Marie
2OD Consulting, Inc. F054 Shere, Brian Thomas
If single quotes enclose a macro
3Administrative Support, Inc. P039 Chevarley, Arlene Elsie variable reference, it is not resolved
4New Time Temps Agency P378 Bates, Ellen Marie by SAS software.

Report Run on 30NOV99 Macro variable references that appear


in quoted strings must be enclosed
in double quotes.
footnote ‘Report Run on &sysdate’;
Macro Variables cannot be defined
with DATALINES
footnote “Report Run on &sysdate”;

SAS Techies 2009 11/13/09 5


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

◦ Whenever you invoke the began executing


SAS System, automatic 16FEB98
macro variables are SYSDATE date the job or session
created that provide such began executing
information as the Tuesday
SYSDAY weekday the job or
◦ date or time a SAS job or
session began executing session began executing
◦ release of SAS software
you are running SYSTIME time the job or session 15:32

◦ name of the most recently began executing


created SAS data set
CMS
◦ abbreviation for your host SYSSCP operating system
operating system. abbreviation
7.0
SYSVER SAS software version
and/or release number
HRD.TEMP99
SYSLAST name of most recently
created data set
SAS Techies 2009 11/13/09 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
variable Sharad in
%let name=sharad;
title "Temporary Employees for Sharad"; the Set dataset
data hrd.temp;
set hrd.temp; if name=“sharad”;

SAS Techies 2009 11/13/09 7


 %let region=northwest;  User-defined macro
 %let region='northwest'; variables enable you to
 %let level=768; substitute a wider range of
 %let lev=&level; resolves to 768 text in your programs
 %let rate=700+700*.05; because you can control the
 %let region =North West ;
values of the 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/13/09 8


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

SAS Techies 2009 11/13/09 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/13/09 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/13/09 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/13/09 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/13/09 13


SAS Techies 2009 11/13/09 14
SAS Techies 2009 11/13/09 15
SAS Techies 2009 11/13/09 16
SAS Techies 2009 11/13/09 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
sharadsasd Scanning
Where sharad is a libname rule
Data &name..sasd - && - &
sharad.sasd

SAS Techies 2009 11/13/09 18


 OPTIONS  SYMBOLGEN specifies
NOSYMBOLGEN | that log messages will
SYMBOLGEN; 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/13/09 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
Argument Result in SAS Log
not specified
_ALL_ Lists the values of all macro variables
◦ does not require quotation
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/13/09 20


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

%let s=%str(;);     %let prog=data


new&s x=1&s run&s;  The %STR function can also be
    %let text=%str(Joan%'s Report);     used to quote tokens that
%let text=Joan%str(%')s Report; typically occur in pairs:
' "  ) (

SAS Techies 2009 11/13/09 21


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

 The %NRSTR function


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

SAS Techies 2009 11/13/09 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/13/09 23


 Because the macro facility  In many applications, you
performs its tasks before need to create macro
SAS programs execute, the variables during DATA
information that the macro step execution. You
facility supplies does not might need to create
depend on values that are macro variables and to
accessed or computed assign values to them
during the execution of a based on
SAS program. ◦ data values in SAS data
sets 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/13/09 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/13/09 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
call symput('total',put(totalovertime,2.)); reference a macro variable
run; that is created with the
SYMPUT routine by preceding
its name with an ampersand
title "Temporary Employees Worked &total OT within the same DATA step in
Hours"; which it is 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/13/09 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 Step character constants, using the
Expressions BEST12. format.
       call symput('due',  The resulting value can be up
trim(left(put(fee*(total- to 32767 characters long.
paidup),dollar8.))));
 Any leading or trailing blanks
 Creating Multiple Macro Variables that are part of the expression
with CALL SYMPUT are stored in the macro
       call symput(course_code, variable.
trim(course_title));
       call symput('teach'||
left(course_number),                   
trim(teacher));

SAS Techies 2009 11/13/09 27


 The INTO clause in a SELECT ◦ the INTO clause cannot be used
statement enables you to when you create a table or a
create or update macro view.
variables.
◦ Most common usage -
proc sql NOPRINT;     select count(*) into :numrows
select course_code, location, begin_date
format=mmddyy10.       
into :crsid1-:crsid3, select course_code,
       :place1-:place3, location,
      :date1-:date3 begin_date
from sasuser.schedule 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/13/09 28


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

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

SAS Techies 2009 11/13/09 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
order to access them in your
code, you must call a macro
be any valid SAS name that is program in order to execute it
not a reserved word in the SAS within your SAS program.
macro facility.
 text can be
◦ constant text, possibly including
 A macro call
SAS data set names, SAS ◦ is specified by placing a percent
variable names, or SAS sign (%) before the name of the
statements macro
◦ macro variables, macro ◦ can be made anywhere in a
functions, or macro program program except within the data
statements lines of a DATALINES statement
◦ any combination of the above. (similar to a macro variable
reference)
◦ requires no semicolon because
it is not a SAS statement.

SAS Techies 2009 11/13/09 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/13/09 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/13/09 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/13/09 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;       To define macros that include
%mend; positional parameters, you
list the names of macro
variables in the %MACRO
 To substitute a null value for statement of the macro
one or more positional definition.
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/13/09 34


 when you use keyword
%macro printdsn(dsn= parameters to create macro
sasuser.courses,vars=course_co variables, you list both the
de name and the value of each
                    course_title days); macro variable in the
  proc print data=&dsn;   macro definition.
   var &vars;
  title "Listing of %upcase(&dsn)  When you call a macro
data set";
  run;     
whose definition includes
keyword parameters, you
%mend;
specify both the keyword
%printdsn(dsn=sasuser.schedule, and the value for each
vars=teacher
              course_code begin_date) 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/13/09 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
proc print data=&dsn;   values before any
var &vars; keyword values, as
title "Listing of follows:
%upcase(&dsn) data set";
run; %macro-name(value-
%mend; 1<,...,value-n>,
                keyword-
1=value-1<,...,keyword-
n=value-n>)

SAS Techies 2009 11/13/09 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/13/09 37


 You can create a global macro  automatic macro variables are
variable with stored in the global symbol table.
◦ a %LET statement (used outside User-defined macro variables that
a macro definition) you create with a %LET statement
in open code (code that is outside
◦ a DATA step that contains a of a macro definition) are also
SYMPUT routine stored in the global symbol table.
◦ a SELECT statement that
contains an INTO clause in PROC
SQL  The global symbol table is created
◦ a %GLOBAL statement. 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/13/09 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
request is made to create a local
◦ a %LET statement within a macro variable during macro execution.
definition
◦ a DATA step that contains a
SYMPUT routine within a macro  The local symbol table is deleted
definition when the macro finishes execution.
◦ a SELECT statement that
contains an INTO clause in PROC  That is, the local symbol table
SQL within a macro definition exists only while the macro
◦ a %LOCAL statement. 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/13/09 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/13/09 40


%macro outer;    Multiple local symbol tables
   %local variX; can exist concurrently
    %let variX=one; during macro execution if you
     %inner    
have 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/13/09 41


Yes

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

No
Yes

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

No

Create macvar in the local symbol table


and assign a value of value to it.

SAS Techies 2009 11/13/09 42


Yes
Does macvar exist in the local symbol table? Retrieve the value of
macvar from the local
symbol table.

No
Yes

Does macvar exist in the global symbol table? Retrieve the value of
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/13/09 43


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

SAS Techies 2009 11/13/09 44


data _null_;  With the iterative %DO
set sasuser.schedule statement you can repeatedly
end=no_more; ◦ execute macro
call symput('teach'||left(_n_), programming code
(trim(teacher)));        ◦ generate SAS code.
if no_more then call
symput('count',_n_);  %DO and %END statements
run; are 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/13/09 45


 The %EVAL function  The %EVAL function does not
◦ translates integer strings convert the following to
and hexadecimal strings to numeric 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/13/09 46


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

SAS Techies 2009 11/13/09 47


OPTIONS MAUTOSOURCE |  You can make macros
NOMAUTOSOURCE; accessible to your SAS
session or program by using
OPTIONS SASAUTOS=(library- the autocall facility to
1,...,library-n); search predefined source
libraries for macro definitions
known as autocall libraries.
Eg:  When you submit a call to
Libname sasmacs that 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/13/09 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
contain compiled macros.
%MACRO macro-name <(parameter-
list)> /STORE
<DES='description'>;
 There are several restrictions on
stored compiled macros.
text
◦ Sasmacr is the only catalog in
%MEND <macro-name>; 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/13/09 49


SAS Techies 2009 11/13/09 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/13/09 51