SlideShare a Scribd company logo
SAS Techies [email_address] http://www.sastechies.com
Creating SAS Tables,  Listings,  Basic Statistics Procedures with SAS  Graphs and ODS HTML Proc Report Advanced SAS Programming Concepts  SAS Macros SQL Joins Match merging  Arrays for Look up TLG’s 11/13/09 SAS Techies 2009
SAS macro variables enable you to substitute text in your SAS programs.  Macro variables can supply a variety of information, from operating system information to SAS session information to any text string you define. By substituting text into programs, SAS macro variables make your programs easy to update  title "Temporary Employees for  1999 ";  data hrd.temp 1999 ;  set hrd.temp; if year(enddate)= 1999 ;  title "Temporary Employees for  2000 ";  data hrd.temp  2000 ;  set hrd.temp; if year(enddate)=  2000 ;  %let yr=1999; title "Temporary Employees for  &yr ";  data hrd.temp &yr ;  set hrd.temp; if year(enddate)=  “&yr” ; & % - Macro facility trigger telling SAS  to resolve the value immediately 11/13/09 SAS Techies 2009
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.  The value of a macro variable is  always   a text string  that becomes part of your program whenever the macro variable is referenced.  %let yr=1999; title "Temporary Employees for  &yr ";  data hrd.temp &yr ;  set hrd.temp; if year(enddate)=  &yr ; 11/13/09 SAS Techies 2009
types of macro variables:  automatic macro variables -  provided by SAS software  user-defined macro variables  – created by the users If single quotes enclose a macro variable reference, it is  not  resolved by SAS software. Macro variable references that appear in quoted strings must be enclosed in  double quotes . Macro Variables cannot be defined with DATALINES footnote "Report Run on &sysdate";  footnote ‘Report Run on &sysdate’;  footnote “Report Run on &sysdate”;  11/13/09 SAS Techies 2009 Obs Agency ID Name 1 Administrative Support, Inc.  F274 Cichock, Elizabeth Marie  2 OD Consulting, Inc.  F054 Shere, Brian Thomas  3 Administrative Support, Inc.  P039 Chevarley, Arlene Elsie 4 New Time Temps Agency  P378 Bates, Ellen Marie Report Run on 30NOV99
Automatic Macro Variables   Whenever you invoke the SAS System, automatic macro variables are created that provide such information as the  date or time a SAS job or session began executing  release of SAS software you are running  name of the most recently created SAS data set  abbreviation for your host operating system.  11/13/09 SAS Techies 2009 Name Information Example SYSDATE9   date the job or session began executing 21APR2000 SYSDATE date the job or session began executing 16FEB98 SYSDAY weekday the job or session began executing Tuesday SYSTIME time the job or session began executing 15:32 SYSSCP operating system abbreviation CMS SYSVER SAS software version and/or release number 7.0 SYSLAST name of most recently created data set HRD.TEMP99
Vimp-The quotes are needed to correctly assign the text string that is contained in the macro variable. If NO quoted are provided SAS looks for the value in the  variable  Sharad  in the Set dataset %let name=sharad; title "Temporary Employees for Sharad";  data hrd.temp;  set hrd.temp; if name=“&name”; %let name=sharad; title "Temporary Employees for Sharad";  data hrd.temp;  set hrd.temp; if name=sharad; %let name=sharad; title "Temporary Employees for Sharad";  data hrd.temp;  set hrd.temp; if name=“sharad”; %let name=sharad; title "Temporary Employees for &name";  data hrd.temp;  set hrd.temp; if name=&name; 11/13/09 SAS Techies 2009
%let region=northwest;  %let region='northwest';  %let level=768;  %let lev=&level;  resolves to 768 %let rate=700+700*.05;  %let region =North West  ; %let region =‘North West  ‘; User-defined macro variables enable you to substitute a wider range of text in your programs because you can control the values of the macro variables.  %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.  11/13/09 SAS Techies 2009
Whether automatic or user-defined, a macro variable is independent of a SAS data set and contains one text string value that remains constant until you change it. The value of a macro variable is substituted into your program wherever the macro variable is referenced.  The value of a macro variable is stored in a  symbol table .  The values of automatic macro variables are always stored in the  global symbol table , meaning that these values are always available in your SAS session.  The values of user-defined macro variables are often stored in the global symbol table as well.  %let  city=Dallas; %local  Date=05JAN2000; %global  amount=975;  11/13/09 SAS Techies 2009 Global Symbol Table SYSTIME 09.47 automatic variables SYSVER 8.01 CITY Dallas user-defined variables DATE 05JAN2000 AMOUNT 975
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.  11/13/09 SAS Techies 2009
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.  11/13/09 SAS Techies 2009
literal  token - Eg: "Any text"  'Any text'  number  token - Eg: 23  109  '01jan2002'd  5e8  42.7  name  token - Eg: infile  _n_  item3  univariate  dollar10.2  special  tokens - Eg: * / +  -  **  ;  $  (  )  .  &  %  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.  The compiler performs a syntax check on the statement.  11/13/09 SAS Techies 2009
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.  11/13/09 SAS Techies 2009
11/13/09 SAS Techies 2009
11/13/09 SAS Techies 2009
11/13/09 SAS Techies 2009
11/13/09 SAS Techies 2009
%let name=sharad;   data hrd. &name ;  data hrd.sharad;  Suppose I want this Data hrd.sharadnew data hrd. &namenew ; data hrd.&name . new Data sharad . sasd Data &name.sasd - sharadsasd Where sharad is a libname Data &name .. sasd - sharad . sasd option symbolgen; %let chakri=Narnindi; %let sharad=chakri; %let name=sharad; %let cool=&&name; %let new=&&&name; %put _user_; Left – right Forward Scanning  rule && - & 11/13/09 SAS Techies 2009
OPTIONS NOSYMBOLGEN  |  SYMBOLGEN;   SYMBOLGEN  specifies that log messages will be displayed.  a message is displayed for each resolved macro variable reference.  When SAS software encounters a macro variable reference but cannot locate a macro variable by that name, the reference is left unresolved and a warning message is generated %let year=1999; title "Temporary Employees for &year";  data hrd.newtemp; set hrd.temp; if year(enddate)= &yera ; run;  title "Temporary Employees for &year";  data hrd.newtemp; set hrd.temp; if year(enddate)= &year ; run;  11/13/09 SAS Techies 2009
General form, basic %PUT statement:   %PUT  text ; - where  text  is any text string.  The %PUT statement  writes only to the SAS log  always writes to a new log line, starting in column one  writes a blank line if text is not specified  does not require quotation marks around text  resolves macro triggers in 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.   11/13/09 SAS Techies 2009 Argument Result in SAS Log _ALL_ Lists the values of all macro variables _AUTOMATIC_ Lists the values of all automatic macro variables _USER_ Lists the values of all user-defined macro variables
%let prog=data new; x=1; run;  &prog      proc print;  Method One:  You could quote all text.  %let prog=%str(data new; x=1; run;); Method Two:  You could quote only the semicolons.  %let prog=data new%str(;)x=1%str(;)run%str(;);  Method Three:  You could create an additional macro variable, assign a quoted value to it, and reference it in the assignment statement for the prog macro variable.  %let s=%str(;);     %let prog=data new&s x=1&s run&s;       %let text=%str(Joan%'s Report);     %let text=Joan%str(%')s Report;  The %STR function is used to mask (or quote) tokens so that the macro processor does not interpret them as macro-level syntax.  They can be used to mask-       ; + - * / , < > = blank  LT  EQ  GT  AND  OR  NOT  LE  GE  NE  The %STR function also  enables macro triggers to work normally  preserves leading and trailing blanks in its argument.  The %STR function can also be used to quote tokens that typically occur in pairs:  ' &quot;  ) (   11/13/09 SAS Techies 2009
%let Period=%str(May&Jun);      %put Period resolves to: &period;     %let Period=%nrstr(May&Jun);      %put Period resolves to: &period;  Sometimes you might want to hide the normal meaning of an ampersand or a percent sign.  The %NRSTR function performs the same quoting function as %STR, except it also masks macro triggers (& and %).  11/13/09 SAS Techies 2009
%upcase where paid=&quot;%upcase(&paidval)&quot;;  %SUBSTR   %substr(&date,3)  %SCAN  %scan(&c,1,*);  %SYSFUNC %sysfunc(today(),weekdate.) %INDEX  %LENGTH  %qupcase %QSUBSTR %QSCAN Function    %QSYSFUNC  11/13/09 SAS Techies 2009
Because 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.  In many applications, you need to create macro variables  during DATA step execution . You might need to create macro variables and to assign values to them based on  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.  11/13/09 SAS Techies 2009
if you need a macro variable to contain a value that is created during the execution of the DATA step, the %LET statement cannot define this macro variable.  CALL SYMPUT(   name , value );   name  is the name of the macro variable to be defined. The variable can be a character string enclosed in quotes, a character variable, or a character expression. value  is the value to be assigned to the macro variable. The value can be a text string enclosed in quotes, a data set variable, or a DATA step expression.  Most often used pulling data with Views…… data hrd.overtime;  set hrd.temp(keep=name overtime); if overtime ne .;  TotalOvertime+overtime;  run; title &quot;Temporary Employees Worked &total OT Hours&quot;;   proc print data=hrd.overtime; run; data hrd.overtime;  set hrd.temp(keep=name overtime); if overtime ne .;  TotalOvertime+overtime;  call symput('total',totalovertime);   run; title &quot;Temporary Employees Worked &total OT Hours&quot;;   proc print data=hrd.overtime; run; 11/13/09 SAS Techies 2009
When you use the SYMPUT routine to create a macro variable in a DATA step, the macro variable is not actually created and assigned a value until the DATA step is  executed . Therefore, you  cannot  successfully reference a macro variable that is created with the SYMPUT routine by preceding its name with an ampersand within the same DATA step in which it is created.  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 data hrd.overtime; set hrd.temp(keep=name overtime); if overtime ne .;  TotalOvertime+overtime;  call symput('total',put(totalovertime,2.)); run; title &quot;Temporary Employees Worked &total OT Hours&quot;;  proc print data=hrd.overtime;  run;  11/13/09 SAS Techies 2009
Using SYMPUT with a Literal  CALL SYMPUT (' macro-variable ',' text ');  Using SYMPUT with a DATA Step Variable  CALL SYMPUT (' macro-variable ', DATA-step-variable );  Using CALL SYMPUT with DATA Step Expressions          call symput(' due ', trim(left( put(fee*(total-paidup),dollar8.) )));  Creating Multiple Macro Variables with CALL SYMPUT          call symput(course_code, trim(course_title));           call symput('teach'||left(course_number),                    trim(teacher));  When you use a DATA step expression as the second argument, its current value is evaluated according to the following rules:  Numeric expressions are  a utomatically converted to character constants, using the BEST12. format.  The resulting value can be up to 32767 characters long.  Any leading or trailing blanks that are part of the expression are stored in the macro variable.  11/13/09 SAS Techies 2009
The INTO clause in a SELECT statement enables you to create or update macro variables.  proc sql  NOPRINT ;     select course_code, location, begin_date format=mmddyy10.         into :crsid1-:crsid3,           :place1-:place3,          :date1-:date3 from sasuser.schedule where year(begin_date)=2002 order by begin_date;     quit;  the INTO clause cannot be used when you create a table or a view.  Most common usage - select  count(*) into :numrows   select course_code,  location,  begin_date format=mmddyy10.     into :crsid1-:crsid &numrows,              :place1-:place &numrows SELECT   column1   INTO   : macro-variable-1   SEPARATED BY  ' delimiter1 '  11/13/09 SAS Techies 2009
SYMGET (‘ macro-variable’ )  %let crsid=C003;       proc sql; create view subcrsid as select student_name,student_company,paid From sasuser.all where course_code= symget('crsid') ;       quit;          teacher=symget('teach'||left(course_number));   11/13/09 SAS Techies 2009 Global Symbol Table TEACH1 Hallis, Dr. George TEACH2 Wickam, Dr. Alice TEACH3 Forest, Mr. Peter CRS 3
%MACRO   macro-name ;  text   %MEND  < macro-name >; where  macro-name  names the macro.  The value of  macro-name  can be any valid SAS name that is not a  reserved word  in the SAS macro facility.  text  can be  constant text, possibly including SAS data set names, SAS variable names, or SAS statements  macro variables, macro functions, or macro program statements  any combination of the above.  After the macro is successfully compiled, you can use it in your SAS programs for the duration of your SAS session without resubmitting the macro definition. Just as you must reference macro variables in order to access them in your code, you must call a macro program in order to execute it within your SAS program.  A  macro call   is specified by placing a percent sign (%) before the name of the macro  can be made anywhere in a 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.  11/13/09 SAS Techies 2009
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 trigge r .  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.  11/13/09 SAS Techies 2009
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… 11/13/09 SAS Techies 2009
%macro prtlast;     proc print data=&syslast(obs=5);   title &quot;Listing of &syslast data set&quot;;    run;  %mend;      data sales;  price_code=1;      run;  options mprint;      %prtlast  11/13/09 SAS Techies 2009
%macro printdsn (dsn,vars) ;        proc print data=&dsn;        var &vars;        title &quot;Listing of %upcase(&dsn) data set&quot;;          run;      %mend;  To substitute a null value for one or more positional parameters, use commas as placeholders for the omitted values, as follows:  %printdsn(,course_code course_title days)  When you include positional parameters in a macro definition, a  local  macro variable is automatically created for each parameter when you call the macro. To define macros that include  positional parameters , you list the names of macro variables in the %MACRO statement of the macro definition.  Positional parameters are so named because the order in which you specify them in a macro definition determines the order in which they are assigned values from the macro call.  11/13/09 SAS Techies 2009
%macro printdsn (dsn= sasuser.courses,vars=course_code                       course_title days) ;    proc print data=&dsn;       var &vars;     title &quot;Listing of %upcase(&dsn) data set&quot;;    run;      %mend;  %printdsn(dsn=sasuser.schedule, vars=teacher               course_code begin_date)  when you use keyword parameters to create macro variables, you list both the name and the value of each macro variable in the macro definition.  When you  call  a macro whose definition includes keyword parameters, you specify both the keyword 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 11/13/09 SAS Techies 2009
%macro printdsn( dsn, vars=course_title course_code days ); proc print data=&dsn;   var &vars; title &quot;Listing of %upcase(&dsn) data set&quot;; run; %mend;  when you  call  a macro that includes a mixed parameter list, you must list the  positional values before any keyword values , as follows:  % macro-name ( value-1<,...,value-n>,                   keyword-1=value-1<,...,keyword-n=value-n> )  11/13/09 SAS Techies 2009
%macro printz/ parmbuff ;   %put Syspbuff contains: &syspbuff;     %let num=1;      %let dsname=%scan( &syspbuff ,&num,’,’); %do %while(&dsname ne  _   ); proc print data=sasuser.&dsname; run; %let num=%eval(&num+1); %let dsname=%scan( &syspbuff ,&num,’,’); %end;       %mend printz;  %printz (dsn1,dsn2, dsn3) Parmbuff option allows to send varying parameter calls to macros. The automatic macro variable SYSPBUFF is used to capture those variable values.display the parameters that are specified in the macro call.  11/13/09 SAS Techies 2009
You can create a global macro variable with  a  %LET statement  (used outside a macro definition)  a DATA step that contains a  SYMPUT routine   a SELECT statement that contains an  INTO clause   in PROC SQL  a %GLOBAL statement.  automatic macro variables are stored in the global symbol table. User-defined macro variables that you create with a %LET statement in open code (code that is outside of a macro definition) are also stored in the global symbol table.  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).  11/13/09 SAS Techies 2009
You can create local macro variables with - parameters in a macro definition  a %LET statement within a macro definition  a DATA step that contains a SYMPUT routine within a macro definition  a SELECT statement that contains an INTO clause in PROC SQL within a macro definition  a %LOCAL statement.  A  local symbol table  is created when a macro that includes a parameter list is called or when a request is made to create a local variable during macro execution.  The local symbol table is deleted when the macro finishes execution.  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.  11/13/09 SAS Techies 2009
%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;  11/13/09 SAS Techies 2009
%macro outer;       %local variX;      %let variX=one;       %inner     %mend outer;       %macro inner;        %local variY;          %let variY=&variX;       %mend inner;  %let variX=zero;    %outer  Multiple local symbol tables can exist  concurrently  during macro execution if you have  nested macros .  That is, if you define a macro program that calls another macro program, and if both macros create local symbol tables, then two local symbol tables will exist while the second macro executes.  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.  11/13/09 SAS Techies 2009
Yes No Yes No 11/13/09 SAS Techies 2009 Does  macvar  already exist in the local symbol table? Update  macvar  in the local symbol table with the value  value .   Does  macvar  already exist in the global symbol table? Update  macvar  in the global symbol table with the value  value .   Create  macvar  in the local symbol table and assign a value of  value  to it.  
Yes No Yes No 11/13/09 SAS Techies 2009 Does  macvar  exist in the local symbol table? Retrieve the value of  macvar  from the local symbol table.   Does  macvar  exist in the global symbol table? Retrieve the value of  macvar  from the global symbol table.   Return the tokens to the word scanner. Issue a warning message to the SAS log to indicate that the reference was not resolved.  
If  expression  resolves to zero, then it is false and the %THEN text is not processed (the optional %ELSE text is processed instead).  %macro choice(status);  data fees; set sasuser.all; %if  &status=PAID  %then %do;           where paid='Y';         keep student_name course_code begin_date totalfee;          %end;     %else %do;            where paid='N';         keep student_name course_code          begin_date totalfee latechg;           latechg=fee*.10;             %end;   Run; %mend choice;  %choice(PAID); 11/13/09 SAS Techies 2009 %IF-%THEN... IF-THEN... is used only in a macro program. is used only in a DATA step program. executes during macro execution. executes during DATA step execution. uses macro variables in logical expressions and cannot refer to DATA step variables in logical expressions. uses DATA step variables in logical expressions. determines what text should be copied to the input stack. determines what DATA step statement(s) should be executed. When inside a macro definition, it is copied to the input stack as text.
data _null_; set sasuser.schedule end=no_more;  call symput('teach'||left(_n_),(trim(teacher)));         if no_more then call symput('count',_n_); run; %macro putloop;       %local i;         %do i=1 %to &count;            %put TEACH&i is &&teach&i;           %end; %mend putloop; %putloop  With the iterative %DO statement you can repeatedly  execute macro programming code  generate SAS code.  %DO and %END statements are valid  only inside  a macro definition  11/13/09 SAS Techies 2009
The %EVAL function  translates integer strings and hexadecimal strings to integers.  translates tokens representing arithmetic, comparison, and logical operators to macro-level operators.  performs arithmetic and logical operations.  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. The %EVAL function  does not  convert the following to numeric values:  numeric strings that contain a period or E-notation  SAS date and time constants.  The %SYSEVALF function performs floating-point arithmetic and returns a value that is formatted using the BEST32. format. The result of the evaluation is always text.  11/13/09 SAS Techies 2009
Code - c:\sasfiles\prtlast.sas     %macro prtlast;      %if &syslast ne _NULL_ %then %do;        proc print data=&syslast(obs=5);          title &quot;Listing of &syslast data set&quot;;        run;         %end;      %else     %put No data set has been created yet.;       %mend;  Your Program %include 'c:\sasfiles\prtlast.sas' /source2; proc sort data=sasuser.courses out=bydays; by days; run; %prtlast   use the %INCLUDE statement to insert the statements that are stored in the external file into a program.  By storing your macro program externally and using the %INCLUDE statement, you gain several advantages over using session-compiled macros.  The source code for the macro definition does not need to be part of your program.  A single copy of a macro definition can be shared by many programs.  Macro definitions in external files are easily viewed and edited with any text editor.  No special SAS system options are required in order to access a macro definition that is stored in an external file.  11/13/09 SAS Techies 2009
OPTIONS MAUTOSOURCE | NOMAUTOSOURCE ;  OPTIONS SASAUTOS= ( library-1,...,library-n) ;  Eg: Libname sasmacs “'c:\mysasfiles'”; options mautosource sasautos=(sasmacs,sasautos);     %prtlast  You can make macros accessible to your SAS session or program by using the  autocall facility  to search predefined source libraries for macro definitions known as  autocall libraries . When you submit a call to that macro,  the macro processor searches the autocall library for the macro  the macro is compiled and stored as it would be if you had submitted it (that is, the compiled macro is stored in the default location of  Work.Sasmacr )  the macro is executed.  11/13/09 SAS Techies 2009
OPTIONS MSTORED | NOMSTORED ;  OPTIONS SASMSTORE= libref ;  %MACRO   macro-name  < (parameter-list) > / STORE   < DES= 'description' > ;   text   %MEND  < macro-name > ;   when a macro is compiled, it is stored in the temporary SAS catalog  Work.Sasmacr  by default. You can also store compiled macros in a permanent SAS catalog to use the  Stored Compiled Macro Facility  to access permanent SAS catalogs that contain compiled macros.  There are several restrictions on stored compiled macros.  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.  11/13/09 SAS Techies 2009
11/13/09 SAS Techies 2009
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 &quot;Report Produced on %sysfunc(left(%sysfunc put(today(),worddate.)))&quot;;  11/13/09 SAS Techies 2009

More Related Content

PDF
SAS cheat sheet
DOCX
SAS Programming Notes
PDF
Sas cheat
PPTX
ADaM - Where Do I Start?
PPT
SAS Proc SQL
PDF
Base SAS Exam Questions
PPTX
Presentation for Tablet Coating
PPTX
Google Forms - A tutorial
SAS cheat sheet
SAS Programming Notes
Sas cheat
ADaM - Where Do I Start?
SAS Proc SQL
Base SAS Exam Questions
Presentation for Tablet Coating
Google Forms - A tutorial

What's hot (20)

PPT
Base SAS Statistics Procedures
PPT
SAS Macros part 1
PDF
Introduction To Sas
PPT
Basics Of SAS Programming Language
PPT
SAS Functions
PPTX
SAS Macro
PPTX
Proc SQL in SAS Enterprise Guide 4.3
PPT
Understanding SAS Data Step Processing
PPT
Data Match Merging in SAS
PPTX
SAS basics Step by step learning
PPT
SAS BASICS
PPT
SAS Macros part 2
PPT
Utility Procedures in SAS
DOCX
Base sas interview questions
PDF
Basics of SAS
PDF
Introduction to sas
PPT
INTRODUCTION TO SAS
PDF
Proc report
PPT
CDISC SDTM Domain Presentation
Base SAS Statistics Procedures
SAS Macros part 1
Introduction To Sas
Basics Of SAS Programming Language
SAS Functions
SAS Macro
Proc SQL in SAS Enterprise Guide 4.3
Understanding SAS Data Step Processing
Data Match Merging in SAS
SAS basics Step by step learning
SAS BASICS
SAS Macros part 2
Utility Procedures in SAS
Base sas interview questions
Basics of SAS
Introduction to sas
INTRODUCTION TO SAS
Proc report
CDISC SDTM Domain Presentation
Ad

Similar to SAS Macros (20)

PPT
Prog1 chap1 and chap 2
PPT
Sas macros part 4.1
PPTX
BAS 150 Lesson 8 Lecture
PPT
SAS Macros part 4.1
PDF
SAS_and_R.pdf
PPTX
SAS macro processing vs with out macro processing
PPT
When best to use the %let statement, the symput routine, or the into clause t...
PPT
Mysql
DOCX
Learn SAS Programming
PDF
224-2009
PPTX
sas.pptxnbhjghjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
PDF
SAS Internal Training
PPTX
01 surya bpc_script_ppt
PPT
Integrate Sas With Google Maps
PDF
Draft sas and r and sas (may, 2018 asa meeting)
PPT
Sax Dom Tutorial
PDF
Proc r
PDF
Task Perform addition subtraction division and multiplic.pdf
PPT
Mazda Use of Third Generation Xml Tools
Prog1 chap1 and chap 2
Sas macros part 4.1
BAS 150 Lesson 8 Lecture
SAS Macros part 4.1
SAS_and_R.pdf
SAS macro processing vs with out macro processing
When best to use the %let statement, the symput routine, or the into clause t...
Mysql
Learn SAS Programming
224-2009
sas.pptxnbhjghjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
SAS Internal Training
01 surya bpc_script_ppt
Integrate Sas With Google Maps
Draft sas and r and sas (may, 2018 asa meeting)
Sax Dom Tutorial
Proc r
Task Perform addition subtraction division and multiplic.pdf
Mazda Use of Third Generation Xml Tools
Ad

More from guest2160992 (6)

PPT
Improving Effeciency with Options in SAS
PPT
Reading Fixed And Varying Data
PPT
Arrays in SAS
PPT
SAS ODS HTML
PPT
Sas Plots Graphs
PPT
SAS Access / SAS Connect
Improving Effeciency with Options in SAS
Reading Fixed And Varying Data
Arrays in SAS
SAS ODS HTML
Sas Plots Graphs
SAS Access / SAS Connect

Recently uploaded (20)

PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Machine learning based COVID-19 study performance prediction
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Cloud computing and distributed systems.
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPT
Teaching material agriculture food technology
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Understanding_Digital_Forensics_Presentation.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Spectroscopy.pptx food analysis technology
MIND Revenue Release Quarter 2 2025 Press Release
Per capita expenditure prediction using model stacking based on satellite ima...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Machine learning based COVID-19 study performance prediction
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Cloud computing and distributed systems.
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Teaching material agriculture food technology
Network Security Unit 5.pdf for BCA BBA.
Building Integrated photovoltaic BIPV_UPV.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Encapsulation_ Review paper, used for researhc scholars
sap open course for s4hana steps from ECC to s4
20250228 LYD VKU AI Blended-Learning.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

SAS Macros

  • 1. SAS Techies [email_address] http://www.sastechies.com
  • 2. Creating SAS Tables, Listings, Basic Statistics Procedures with SAS Graphs and ODS HTML Proc Report Advanced SAS Programming Concepts SAS Macros SQL Joins Match merging Arrays for Look up TLG’s 11/13/09 SAS Techies 2009
  • 3. SAS macro variables enable you to substitute text in your SAS programs. Macro variables can supply a variety of information, from operating system information to SAS session information to any text string you define. By substituting text into programs, SAS macro variables make your programs easy to update title &quot;Temporary Employees for 1999 &quot;; data hrd.temp 1999 ; set hrd.temp; if year(enddate)= 1999 ; title &quot;Temporary Employees for 2000 &quot;; data hrd.temp 2000 ; set hrd.temp; if year(enddate)= 2000 ; %let yr=1999; title &quot;Temporary Employees for &yr &quot;; data hrd.temp &yr ; set hrd.temp; if year(enddate)= “&yr” ; & % - Macro facility trigger telling SAS to resolve the value immediately 11/13/09 SAS Techies 2009
  • 4. 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. The value of a macro variable is always a text string that becomes part of your program whenever the macro variable is referenced. %let yr=1999; title &quot;Temporary Employees for &yr &quot;; data hrd.temp &yr ; set hrd.temp; if year(enddate)= &yr ; 11/13/09 SAS Techies 2009
  • 5. types of macro variables: automatic macro variables - provided by SAS software user-defined macro variables – created by the users If single quotes enclose a macro variable reference, it is not resolved by SAS software. Macro variable references that appear in quoted strings must be enclosed in double quotes . Macro Variables cannot be defined with DATALINES footnote &quot;Report Run on &sysdate&quot;; footnote ‘Report Run on &sysdate’; footnote “Report Run on &sysdate”; 11/13/09 SAS Techies 2009 Obs Agency ID Name 1 Administrative Support, Inc. F274 Cichock, Elizabeth Marie 2 OD Consulting, Inc. F054 Shere, Brian Thomas 3 Administrative Support, Inc. P039 Chevarley, Arlene Elsie 4 New Time Temps Agency P378 Bates, Ellen Marie Report Run on 30NOV99
  • 6. Automatic Macro Variables Whenever you invoke the SAS System, automatic macro variables are created that provide such information as the date or time a SAS job or session began executing release of SAS software you are running name of the most recently created SAS data set abbreviation for your host operating system. 11/13/09 SAS Techies 2009 Name Information Example SYSDATE9   date the job or session began executing 21APR2000 SYSDATE date the job or session began executing 16FEB98 SYSDAY weekday the job or session began executing Tuesday SYSTIME time the job or session began executing 15:32 SYSSCP operating system abbreviation CMS SYSVER SAS software version and/or release number 7.0 SYSLAST name of most recently created data set HRD.TEMP99
  • 7. Vimp-The quotes are needed to correctly assign the text string that is contained in the macro variable. If NO quoted are provided SAS looks for the value in the variable Sharad in the Set dataset %let name=sharad; title &quot;Temporary Employees for Sharad&quot;; data hrd.temp; set hrd.temp; if name=“&name”; %let name=sharad; title &quot;Temporary Employees for Sharad&quot;; data hrd.temp; set hrd.temp; if name=sharad; %let name=sharad; title &quot;Temporary Employees for Sharad&quot;; data hrd.temp; set hrd.temp; if name=“sharad”; %let name=sharad; title &quot;Temporary Employees for &name&quot;; data hrd.temp; set hrd.temp; if name=&name; 11/13/09 SAS Techies 2009
  • 8. %let region=northwest; %let region='northwest'; %let level=768; %let lev=&level; resolves to 768 %let rate=700+700*.05; %let region =North West ; %let region =‘North West ‘; User-defined macro variables enable you to substitute a wider range of text in your programs because you can control the values of the macro variables. %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. 11/13/09 SAS Techies 2009
  • 9. Whether automatic or user-defined, a macro variable is independent of a SAS data set and contains one text string value that remains constant until you change it. The value of a macro variable is substituted into your program wherever the macro variable is referenced. The value of a macro variable is stored in a symbol table . The values of automatic macro variables are always stored in the global symbol table , meaning that these values are always available in your SAS session. The values of user-defined macro variables are often stored in the global symbol table as well. %let city=Dallas; %local Date=05JAN2000; %global amount=975; 11/13/09 SAS Techies 2009 Global Symbol Table SYSTIME 09.47 automatic variables SYSVER 8.01 CITY Dallas user-defined variables DATE 05JAN2000 AMOUNT 975
  • 10. 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. 11/13/09 SAS Techies 2009
  • 11. 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. 11/13/09 SAS Techies 2009
  • 12. literal token - Eg: &quot;Any text&quot;  'Any text' number token - Eg: 23  109  '01jan2002'd  5e8  42.7 name token - Eg: infile  _n_  item3  univariate  dollar10.2 special tokens - Eg: * / +  -  **  ;  $  (  )  .  &  % 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. The compiler performs a syntax check on the statement. 11/13/09 SAS Techies 2009
  • 13. 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. 11/13/09 SAS Techies 2009
  • 18. %let name=sharad; data hrd. &name ; data hrd.sharad; Suppose I want this Data hrd.sharadnew data hrd. &namenew ; data hrd.&name . new Data sharad . sasd Data &name.sasd - sharadsasd Where sharad is a libname Data &name .. sasd - sharad . sasd option symbolgen; %let chakri=Narnindi; %let sharad=chakri; %let name=sharad; %let cool=&&name; %let new=&&&name; %put _user_; Left – right Forward Scanning rule && - & 11/13/09 SAS Techies 2009
  • 19. OPTIONS NOSYMBOLGEN | SYMBOLGEN; SYMBOLGEN specifies that log messages will be displayed. a message is displayed for each resolved macro variable reference. When SAS software encounters a macro variable reference but cannot locate a macro variable by that name, the reference is left unresolved and a warning message is generated %let year=1999; title &quot;Temporary Employees for &year&quot;; data hrd.newtemp; set hrd.temp; if year(enddate)= &yera ; run; title &quot;Temporary Employees for &year&quot;; data hrd.newtemp; set hrd.temp; if year(enddate)= &year ; run; 11/13/09 SAS Techies 2009
  • 20. General form, basic %PUT statement: %PUT text ; - where text is any text string. The %PUT statement writes only to the SAS log always writes to a new log line, starting in column one writes a blank line if text is not specified does not require quotation marks around text resolves macro triggers in 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.   11/13/09 SAS Techies 2009 Argument Result in SAS Log _ALL_ Lists the values of all macro variables _AUTOMATIC_ Lists the values of all automatic macro variables _USER_ Lists the values of all user-defined macro variables
  • 21. %let prog=data new; x=1; run; &prog     proc print; Method One: You could quote all text. %let prog=%str(data new; x=1; run;); Method Two: You could quote only the semicolons. %let prog=data new%str(;)x=1%str(;)run%str(;); Method Three: You could create an additional macro variable, assign a quoted value to it, and reference it in the assignment statement for the prog macro variable. %let s=%str(;);     %let prog=data new&s x=1&s run&s;     %let text=%str(Joan%'s Report);     %let text=Joan%str(%')s Report; The %STR function is used to mask (or quote) tokens so that the macro processor does not interpret them as macro-level syntax. They can be used to mask-      ; + - * / , < > = blank LT  EQ  GT  AND  OR  NOT  LE  GE  NE The %STR function also enables macro triggers to work normally preserves leading and trailing blanks in its argument. The %STR function can also be used to quote tokens that typically occur in pairs: ' &quot;  ) ( 11/13/09 SAS Techies 2009
  • 22. %let Period=%str(May&Jun);     %put Period resolves to: &period;     %let Period=%nrstr(May&Jun);     %put Period resolves to: &period; Sometimes you might want to hide the normal meaning of an ampersand or a percent sign. The %NRSTR function performs the same quoting function as %STR, except it also masks macro triggers (& and %). 11/13/09 SAS Techies 2009
  • 23. %upcase where paid=&quot;%upcase(&paidval)&quot;; %SUBSTR %substr(&date,3) %SCAN %scan(&c,1,*); %SYSFUNC %sysfunc(today(),weekdate.) %INDEX %LENGTH %qupcase %QSUBSTR %QSCAN Function   %QSYSFUNC 11/13/09 SAS Techies 2009
  • 24. Because 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. In many applications, you need to create macro variables during DATA step execution . You might need to create macro variables and to assign values to them based on 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. 11/13/09 SAS Techies 2009
  • 25. if you need a macro variable to contain a value that is created during the execution of the DATA step, the %LET statement cannot define this macro variable. CALL SYMPUT( name , value ); name is the name of the macro variable to be defined. The variable can be a character string enclosed in quotes, a character variable, or a character expression. value is the value to be assigned to the macro variable. The value can be a text string enclosed in quotes, a data set variable, or a DATA step expression. Most often used pulling data with Views…… data hrd.overtime; set hrd.temp(keep=name overtime); if overtime ne .; TotalOvertime+overtime; run; title &quot;Temporary Employees Worked &total OT Hours&quot;; proc print data=hrd.overtime; run; data hrd.overtime; set hrd.temp(keep=name overtime); if overtime ne .; TotalOvertime+overtime; call symput('total',totalovertime); run; title &quot;Temporary Employees Worked &total OT Hours&quot;; proc print data=hrd.overtime; run; 11/13/09 SAS Techies 2009
  • 26. When you use the SYMPUT routine to create a macro variable in a DATA step, the macro variable is not actually created and assigned a value until the DATA step is executed . Therefore, you cannot successfully reference a macro variable that is created with the SYMPUT routine by preceding its name with an ampersand within the same DATA step in which it is created. 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 data hrd.overtime; set hrd.temp(keep=name overtime); if overtime ne .; TotalOvertime+overtime; call symput('total',put(totalovertime,2.)); run; title &quot;Temporary Employees Worked &total OT Hours&quot;; proc print data=hrd.overtime; run; 11/13/09 SAS Techies 2009
  • 27. Using SYMPUT with a Literal CALL SYMPUT (' macro-variable ',' text '); Using SYMPUT with a DATA Step Variable CALL SYMPUT (' macro-variable ', DATA-step-variable ); Using CALL SYMPUT with DATA Step Expressions        call symput(' due ', trim(left( put(fee*(total-paidup),dollar8.) ))); Creating Multiple Macro Variables with CALL SYMPUT        call symput(course_code, trim(course_title));        call symput('teach'||left(course_number),                    trim(teacher)); When you use a DATA step expression as the second argument, its current value is evaluated according to the following rules: Numeric expressions are a utomatically converted to character constants, using the BEST12. format. The resulting value can be up to 32767 characters long. Any leading or trailing blanks that are part of the expression are stored in the macro variable. 11/13/09 SAS Techies 2009
  • 28. The INTO clause in a SELECT statement enables you to create or update macro variables. proc sql NOPRINT ;     select course_code, location, begin_date format=mmddyy10.        into :crsid1-:crsid3,        :place1-:place3,        :date1-:date3 from sasuser.schedule where year(begin_date)=2002 order by begin_date;     quit; the INTO clause cannot be used when you create a table or a view. Most common usage - select count(*) into :numrows select course_code, location, begin_date format=mmddyy10.    into :crsid1-:crsid &numrows,            :place1-:place &numrows SELECT column1 INTO : macro-variable-1 SEPARATED BY ' delimiter1 ' 11/13/09 SAS Techies 2009
  • 29. SYMGET (‘ macro-variable’ ) %let crsid=C003;     proc sql; create view subcrsid as select student_name,student_company,paid From sasuser.all where course_code= symget('crsid') ;     quit;        teacher=symget('teach'||left(course_number)); 11/13/09 SAS Techies 2009 Global Symbol Table TEACH1 Hallis, Dr. George TEACH2 Wickam, Dr. Alice TEACH3 Forest, Mr. Peter CRS 3
  • 30. %MACRO macro-name ; text %MEND < macro-name >; where macro-name names the macro. The value of macro-name can be any valid SAS name that is not a reserved word in the SAS macro facility. text can be constant text, possibly including SAS data set names, SAS variable names, or SAS statements macro variables, macro functions, or macro program statements any combination of the above. After the macro is successfully compiled, you can use it in your SAS programs for the duration of your SAS session without resubmitting the macro definition. Just as you must reference macro variables in order to access them in your code, you must call a macro program in order to execute it within your SAS program. A macro call is specified by placing a percent sign (%) before the name of the macro can be made anywhere in a 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. 11/13/09 SAS Techies 2009
  • 31. 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 trigge r . 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. 11/13/09 SAS Techies 2009
  • 32. 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… 11/13/09 SAS Techies 2009
  • 33. %macro prtlast;    proc print data=&syslast(obs=5);   title &quot;Listing of &syslast data set&quot;;    run; %mend;     data sales; price_code=1;     run; options mprint;     %prtlast 11/13/09 SAS Techies 2009
  • 34. %macro printdsn (dsn,vars) ;      proc print data=&dsn;       var &vars;       title &quot;Listing of %upcase(&dsn) data set&quot;;          run;      %mend; To substitute a null value for one or more positional parameters, use commas as placeholders for the omitted values, as follows: %printdsn(,course_code course_title days) When you include positional parameters in a macro definition, a local macro variable is automatically created for each parameter when you call the macro. To define macros that include positional parameters , you list the names of macro variables in the %MACRO statement of the macro definition. Positional parameters are so named because the order in which you specify them in a macro definition determines the order in which they are assigned values from the macro call. 11/13/09 SAS Techies 2009
  • 35. %macro printdsn (dsn= sasuser.courses,vars=course_code                      course_title days) ;   proc print data=&dsn;      var &vars;   title &quot;Listing of %upcase(&dsn) data set&quot;;   run;      %mend; %printdsn(dsn=sasuser.schedule, vars=teacher               course_code begin_date) when you use keyword parameters to create macro variables, you list both the name and the value of each macro variable in the macro definition. When you call a macro whose definition includes keyword parameters, you specify both the keyword 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 11/13/09 SAS Techies 2009
  • 36. %macro printdsn( dsn, vars=course_title course_code days ); proc print data=&dsn;   var &vars; title &quot;Listing of %upcase(&dsn) data set&quot;; run; %mend; when you call a macro that includes a mixed parameter list, you must list the positional values before any keyword values , as follows: % macro-name ( value-1<,...,value-n>,                 keyword-1=value-1<,...,keyword-n=value-n> ) 11/13/09 SAS Techies 2009
  • 37. %macro printz/ parmbuff ;   %put Syspbuff contains: &syspbuff;   %let num=1;     %let dsname=%scan( &syspbuff ,&num,’,’); %do %while(&dsname ne _ ); proc print data=sasuser.&dsname; run; %let num=%eval(&num+1); %let dsname=%scan( &syspbuff ,&num,’,’); %end;      %mend printz; %printz (dsn1,dsn2, dsn3) Parmbuff option allows to send varying parameter calls to macros. The automatic macro variable SYSPBUFF is used to capture those variable values.display the parameters that are specified in the macro call. 11/13/09 SAS Techies 2009
  • 38. You can create a global macro variable with a %LET statement (used outside a macro definition) a DATA step that contains a SYMPUT routine a SELECT statement that contains an INTO clause in PROC SQL a %GLOBAL statement. automatic macro variables are stored in the global symbol table. User-defined macro variables that you create with a %LET statement in open code (code that is outside of a macro definition) are also stored in the global symbol table. 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). 11/13/09 SAS Techies 2009
  • 39. You can create local macro variables with - parameters in a macro definition a %LET statement within a macro definition a DATA step that contains a SYMPUT routine within a macro definition a SELECT statement that contains an INTO clause in PROC SQL within a macro definition a %LOCAL statement. A local symbol table is created when a macro that includes a parameter list is called or when a request is made to create a local variable during macro execution. The local symbol table is deleted when the macro finishes execution. 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. 11/13/09 SAS Techies 2009
  • 40. %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; 11/13/09 SAS Techies 2009
  • 41. %macro outer;      %local variX;     %let variX=one;      %inner     %mend outer;     %macro inner;       %local variY;        %let variY=&variX;      %mend inner; %let variX=zero;    %outer Multiple local symbol tables can exist concurrently during macro execution if you have nested macros . That is, if you define a macro program that calls another macro program, and if both macros create local symbol tables, then two local symbol tables will exist while the second macro executes. 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. 11/13/09 SAS Techies 2009
  • 42. Yes No Yes No 11/13/09 SAS Techies 2009 Does macvar already exist in the local symbol table? Update macvar in the local symbol table with the value value .   Does macvar already exist in the global symbol table? Update macvar in the global symbol table with the value value .   Create macvar in the local symbol table and assign a value of value to it.  
  • 43. Yes No Yes No 11/13/09 SAS Techies 2009 Does macvar exist in the local symbol table? Retrieve the value of macvar from the local symbol table.   Does macvar exist in the global symbol table? Retrieve the value of macvar from the global symbol table.   Return the tokens to the word scanner. Issue a warning message to the SAS log to indicate that the reference was not resolved.  
  • 44. If expression resolves to zero, then it is false and the %THEN text is not processed (the optional %ELSE text is processed instead). %macro choice(status); data fees; set sasuser.all; %if &status=PAID %then %do;        where paid='Y';         keep student_name course_code begin_date totalfee;        %end;    %else %do;         where paid='N';        keep student_name course_code        begin_date totalfee latechg;          latechg=fee*.10;            %end; Run; %mend choice; %choice(PAID); 11/13/09 SAS Techies 2009 %IF-%THEN... IF-THEN... is used only in a macro program. is used only in a DATA step program. executes during macro execution. executes during DATA step execution. uses macro variables in logical expressions and cannot refer to DATA step variables in logical expressions. uses DATA step variables in logical expressions. determines what text should be copied to the input stack. determines what DATA step statement(s) should be executed. When inside a macro definition, it is copied to the input stack as text.
  • 45. data _null_; set sasuser.schedule end=no_more; call symput('teach'||left(_n_),(trim(teacher)));        if no_more then call symput('count',_n_); run; %macro putloop;      %local i;        %do i=1 %to &count;           %put TEACH&i is &&teach&i;        %end; %mend putloop; %putloop With the iterative %DO statement you can repeatedly execute macro programming code generate SAS code. %DO and %END statements are valid only inside a macro definition 11/13/09 SAS Techies 2009
  • 46. The %EVAL function translates integer strings and hexadecimal strings to integers. translates tokens representing arithmetic, comparison, and logical operators to macro-level operators. performs arithmetic and logical operations. 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. The %EVAL function does not convert the following to numeric values: numeric strings that contain a period or E-notation SAS date and time constants. The %SYSEVALF function performs floating-point arithmetic and returns a value that is formatted using the BEST32. format. The result of the evaluation is always text. 11/13/09 SAS Techies 2009
  • 47. Code - c:\sasfiles\prtlast.sas    %macro prtlast;     %if &syslast ne _NULL_ %then %do;       proc print data=&syslast(obs=5);         title &quot;Listing of &syslast data set&quot;;       run;        %end;     %else    %put No data set has been created yet.;     %mend; Your Program %include 'c:\sasfiles\prtlast.sas' /source2; proc sort data=sasuser.courses out=bydays; by days; run; %prtlast use the %INCLUDE statement to insert the statements that are stored in the external file into a program. By storing your macro program externally and using the %INCLUDE statement, you gain several advantages over using session-compiled macros. The source code for the macro definition does not need to be part of your program. A single copy of a macro definition can be shared by many programs. Macro definitions in external files are easily viewed and edited with any text editor. No special SAS system options are required in order to access a macro definition that is stored in an external file. 11/13/09 SAS Techies 2009
  • 48. OPTIONS MAUTOSOURCE | NOMAUTOSOURCE ; OPTIONS SASAUTOS= ( library-1,...,library-n) ; Eg: Libname sasmacs “'c:\mysasfiles'”; options mautosource sasautos=(sasmacs,sasautos);     %prtlast You can make macros accessible to your SAS session or program by using the autocall facility to search predefined source libraries for macro definitions known as autocall libraries . When you submit a call to that macro, the macro processor searches the autocall library for the macro the macro is compiled and stored as it would be if you had submitted it (that is, the compiled macro is stored in the default location of Work.Sasmacr ) the macro is executed. 11/13/09 SAS Techies 2009
  • 49. OPTIONS MSTORED | NOMSTORED ; OPTIONS SASMSTORE= libref ; %MACRO macro-name < (parameter-list) > / STORE < DES= 'description' > ; text %MEND < macro-name > ; when a macro is compiled, it is stored in the temporary SAS catalog Work.Sasmacr by default. You can also store compiled macros in a permanent SAS catalog to use the Stored Compiled Macro Facility to access permanent SAS catalogs that contain compiled macros. There are several restrictions on stored compiled macros. 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. 11/13/09 SAS Techies 2009
  • 51. 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 &quot;Report Produced on %sysfunc(left(%sysfunc put(today(),worddate.)))&quot;; 11/13/09 SAS Techies 2009

Editor's Notes

  • #2: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #3: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #4: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #5: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #6: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #7: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #8: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #9: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #10: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #11: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #12: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #13: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #14: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #15: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #16: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #17: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #18: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #19: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #20: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #21: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #22: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #23: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #24: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #25: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #26: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #27: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #28: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #29: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #30: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #31: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #32: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #33: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #34: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #35: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #36: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #37: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #38: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #39: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #40: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #41: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #42: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #43: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #44: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #45: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #46: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #47: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #48: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #49: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #50: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #51: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005
  • #52: SASTechies.com Sharad C Narnindi - Attic Technologies,Inc 2005