SAS Macros

12,465 views

Published on

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

visit http://sastechies.blogspot.com

Published in: Technology
  • Hi All, We are planning to start Hadoop online training batch on this week... If any one interested to attend the demo please register in our website... For this batch we are also provide everyday recorded sessions with Materials. For more information feel free to contact us : siva@keylabstraining.com. For Course Content and Recorded Demo Click Here : http://www.keylabstraining.com/hadoop-online-training-hyderabad-bangalore
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • To know & learn SAS macros
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

SAS Macros

  1. 1. SAS Techies [email_address] http://www.sastechies.com
  2. 2. <ul><li>Creating </li></ul><ul><ul><li>SAS Tables, </li></ul></ul><ul><ul><li>Listings, </li></ul></ul><ul><ul><li>Basic Statistics Procedures with SAS </li></ul></ul><ul><ul><li>Graphs </li></ul></ul><ul><ul><li>and ODS HTML </li></ul></ul><ul><ul><li>Proc Report </li></ul></ul><ul><li>Advanced SAS Programming Concepts </li></ul><ul><ul><li>SAS Macros </li></ul></ul><ul><ul><li>SQL Joins </li></ul></ul><ul><ul><li>Match merging </li></ul></ul><ul><ul><li>Arrays for Look up </li></ul></ul>TLG’s 11/13/09 SAS Techies 2009
  3. 3. <ul><li>SAS macro variables enable you to substitute text in your SAS programs. </li></ul><ul><li>Macro variables can supply a variety of information, from operating system information to SAS session information to any text string you define. </li></ul><ul><li>By substituting text into programs, SAS macro variables make your programs easy to update </li></ul>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. 4. <ul><li>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. </li></ul><ul><li>A macro variable is independent of a SAS data set and contains one value that remains constant until you change it. </li></ul><ul><li>The value of a macro variable is always a text string that becomes part of your program whenever the macro variable is referenced. </li></ul>%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. 5. <ul><li>types of macro variables: </li></ul><ul><ul><li>automatic macro variables - provided by SAS software </li></ul></ul><ul><ul><li>user-defined macro variables – created by the users </li></ul></ul><ul><ul><li>If single quotes enclose a macro variable reference, it is not resolved by SAS software. </li></ul></ul><ul><ul><li>Macro variable references that appear in quoted strings must be enclosed in double quotes . </li></ul></ul><ul><ul><li>Macro Variables cannot be defined with DATALINES </li></ul></ul>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. 6. <ul><li>Automatic Macro Variables </li></ul><ul><ul><li>Whenever you invoke the SAS System, automatic macro variables are created that provide such information as the </li></ul></ul><ul><ul><li>date or time a SAS job or session began executing </li></ul></ul><ul><ul><li>release of SAS software you are running </li></ul></ul><ul><ul><li>name of the most recently created SAS data set </li></ul></ul><ul><ul><li>abbreviation for your host operating system. </li></ul></ul>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. 7. <ul><li>Vimp-The quotes are needed to correctly assign the text string that is contained in the macro variable. </li></ul><ul><li>If NO quoted are provided SAS looks for the value in the variable Sharad in the Set dataset </li></ul>%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. 8. <ul><li>%let region=northwest; </li></ul><ul><li>%let region='northwest'; </li></ul><ul><li>%let level=768; </li></ul><ul><li>%let lev=&level; resolves to 768 </li></ul><ul><li>%let rate=700+700*.05; </li></ul><ul><li>%let region =North West ; </li></ul><ul><li>%let region =‘North West ‘; </li></ul><ul><li>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. </li></ul><ul><li>%LET name=value ; </li></ul><ul><li>Everything appearing between the equal sign and semicolon is considered part of the macro variable value. </li></ul><ul><li>%let removes all leading and trailing blank spaces by default except when in quotes; </li></ul><ul><li>The use of the SYS prefix is reserved to SAS software for automatic macro variable names. </li></ul>11/13/09 SAS Techies 2009
  9. 9. <ul><li>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. </li></ul><ul><li>The value of a macro variable is stored in a symbol table . </li></ul><ul><li>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. </li></ul><ul><li>The values of user-defined macro variables are often stored in the global symbol table as well. </li></ul><ul><li>%let city=Dallas; </li></ul><ul><li>%local Date=05JAN2000; </li></ul><ul><li>%global amount=975; </li></ul>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. 10. <ul><li>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. </li></ul><ul><li>Once SAS code is in the input stack, SAS </li></ul><ul><ul><li>reads the text in the input stack (left-to-right, top-to-bottom) </li></ul></ul><ul><ul><li>routes text to the appropriate compiler upon demand </li></ul></ul><ul><ul><li>suspends this activity when a step boundary such as a RUN statement is reached </li></ul></ul><ul><ul><li>executes the compiled code if there are no compilation errors </li></ul></ul><ul><ul><li>repeats this process for any subsequent steps. </li></ul></ul>11/13/09 SAS Techies 2009
  11. 11. <ul><li>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. </li></ul>11/13/09 SAS Techies 2009
  12. 12. <ul><li>literal token - Eg: &quot;Any text&quot;  'Any text' </li></ul><ul><li>number token - Eg: 23  109  '01jan2002'd  5e8  42.7 </li></ul><ul><li>name token - Eg: infile  _n_  item3  univariate  dollar10.2 </li></ul><ul><li>special tokens - Eg: * / +  -  **  ;  $  (  )  .  &  % </li></ul><ul><li>Between the input stack and the compiler, SAS programs are tokenized into smaller pieces. </li></ul><ul><li>A component of SAS known as the word scanner divides program text into fundamental units called tokens . </li></ul><ul><ul><li>Tokens are passed on demand to the compiler. </li></ul></ul><ul><ul><li>The compiler requests tokens until it receives a semicolon. </li></ul></ul><ul><ul><li>The compiler performs a syntax check on the statement. </li></ul></ul>11/13/09 SAS Techies 2009
  13. 13. <ul><li>Macro Triggers </li></ul><ul><ul><li>% followed immediately by a name token (such as %let ) </li></ul></ul><ul><ul><li>& followed immediately by a name token (such as &amt ). </li></ul></ul><ul><li>When a macro trigger is detected, the word scanner passes it to the macro processor for evaluation. </li></ul><ul><li>For macro variables, the processor does one of the following: </li></ul><ul><ul><li>creates a macro variable in the symbol table and assigns a value to the variable </li></ul></ul><ul><ul><li>changes the value of an existing macro variable in the symbol table </li></ul></ul><ul><ul><li>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. </li></ul></ul>11/13/09 SAS Techies 2009
  14. 14. 11/13/09 SAS Techies 2009
  15. 15. 11/13/09 SAS Techies 2009
  16. 16. 11/13/09 SAS Techies 2009
  17. 17. 11/13/09 SAS Techies 2009
  18. 18. <ul><li>%let name=sharad; </li></ul><ul><li>data hrd. &name ; </li></ul><ul><li>data hrd.sharad; </li></ul><ul><li>Suppose I want this </li></ul><ul><li>Data hrd.sharadnew </li></ul><ul><li>data hrd. &namenew ; </li></ul><ul><li>data hrd.&name . new </li></ul><ul><li>Data sharad . sasd </li></ul><ul><li>Data &name.sasd - sharadsasd </li></ul><ul><li>Where sharad is a libname </li></ul><ul><li>Data &name .. sasd - sharad . sasd </li></ul><ul><li>option symbolgen; </li></ul><ul><li>%let chakri=Narnindi; </li></ul><ul><li>%let sharad=chakri; </li></ul><ul><li>%let name=sharad; </li></ul><ul><li>%let cool=&&name; </li></ul><ul><li>%let new=&&&name; </li></ul><ul><li>%put _user_; </li></ul><ul><li>Left – right Forward Scanning </li></ul><ul><li>rule </li></ul><ul><li>&& - & </li></ul>11/13/09 SAS Techies 2009
  19. 19. <ul><li>OPTIONS NOSYMBOLGEN | SYMBOLGEN; </li></ul><ul><li>SYMBOLGEN specifies that log messages will be displayed. </li></ul><ul><li>a message is displayed for each resolved macro variable reference. </li></ul><ul><li>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 </li></ul>%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. 20. <ul><li>General form, basic %PUT statement: </li></ul><ul><ul><li>%PUT text ; - where text is any text string. </li></ul></ul><ul><li>The %PUT statement </li></ul><ul><ul><li>writes only to the SAS log </li></ul></ul><ul><ul><li>always writes to a new log line, starting in column one </li></ul></ul><ul><ul><li>writes a blank line if text is not specified </li></ul></ul><ul><ul><li>does not require quotation marks around text </li></ul></ul><ul><ul><li>resolves macro triggers in text before text is written </li></ul></ul><ul><ul><li>removes leading and trailing blanks from text unless a macro quoting function is used </li></ul></ul><ul><ul><li>wraps lines when the length of text is greater than the current line size setting </li></ul></ul><ul><ul><li>can be used either inside or outside a macro definition.   </li></ul></ul>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. 21. <ul><li>%let prog=data new; x=1; run; </li></ul><ul><li>&prog     </li></ul><ul><li>proc print; </li></ul><ul><li>Method One: You could quote all text. </li></ul><ul><li>%let prog=%str(data new; x=1; run;); </li></ul><ul><li>Method Two: You could quote only the semicolons. </li></ul><ul><li>%let prog=data new%str(;)x=1%str(;)run%str(;); </li></ul><ul><li>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. </li></ul><ul><li>%let s=%str(;);     %let prog=data new&s x=1&s run&s; </li></ul><ul><li>    %let text=%str(Joan%'s Report);     %let text=Joan%str(%')s Report; </li></ul><ul><li>The %STR function is used to mask (or quote) tokens so that the macro processor does not interpret them as macro-level syntax. </li></ul><ul><li>They can be used to mask- </li></ul><ul><li>     ; + - * / , < > = blank LT  EQ  </li></ul><ul><li>GT  AND  OR  NOT  LE  GE  NE </li></ul><ul><li>The %STR function also </li></ul><ul><ul><li>enables macro triggers to work normally </li></ul></ul><ul><ul><li>preserves leading and trailing blanks in its argument. </li></ul></ul><ul><li>The %STR function can also be used to quote tokens that typically occur in pairs: </li></ul><ul><li>' &quot;  ) ( </li></ul>11/13/09 SAS Techies 2009
  22. 22. <ul><li>%let Period=%str(May&Jun); </li></ul><ul><li>    %put Period resolves to: &period;   </li></ul><ul><li>  </li></ul><ul><li>%let Period=%nrstr(May&Jun); </li></ul><ul><li>    %put Period resolves to: &period; </li></ul><ul><li>Sometimes you might want to hide the normal meaning of an ampersand or a percent sign. </li></ul><ul><li>The %NRSTR function performs the same quoting function as %STR, except it also masks macro triggers (& and %). </li></ul>11/13/09 SAS Techies 2009
  23. 23. <ul><li>%upcase </li></ul><ul><li>where paid=&quot;%upcase(&paidval)&quot;; </li></ul><ul><li>%SUBSTR </li></ul><ul><li>%substr(&date,3) </li></ul><ul><li>%SCAN </li></ul><ul><li>%scan(&c,1,*); </li></ul><ul><li>%SYSFUNC </li></ul><ul><li>%sysfunc(today(),weekdate.) </li></ul><ul><li>%INDEX </li></ul><ul><li>%LENGTH </li></ul><ul><li>%qupcase </li></ul><ul><li>%QSUBSTR </li></ul><ul><li>%QSCAN Function </li></ul><ul><li>  %QSYSFUNC </li></ul>11/13/09 SAS Techies 2009
  24. 24. <ul><li>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. </li></ul><ul><li>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 </li></ul><ul><ul><li>data values in SAS data sets or in external files </li></ul></ul><ul><ul><li>programming logic </li></ul></ul><ul><ul><li>computed values. </li></ul></ul><ul><li>  The DATA step provides functions and CALL routines that enable you to transfer information between an executing DATA step and the macro processor. </li></ul>11/13/09 SAS Techies 2009
  25. 25. <ul><li>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. </li></ul><ul><li>CALL SYMPUT( name , value ); </li></ul><ul><ul><li>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. </li></ul></ul><ul><ul><li>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. </li></ul></ul><ul><ul><li>Most often used pulling data with Views…… </li></ul></ul>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. 26. <ul><li>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. </li></ul><ul><li>When converting numeric to character remember every numeric value is in the BEST12. format. </li></ul><ul><li>Take care of it by using formats, trim(left()) combinations, scan, substr,compress functions </li></ul>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. 27. <ul><li>Using SYMPUT with a Literal </li></ul><ul><li>CALL SYMPUT (' macro-variable ',' text '); </li></ul><ul><li>Using SYMPUT with a DATA Step Variable </li></ul><ul><li>CALL SYMPUT (' macro-variable ', DATA-step-variable ); </li></ul><ul><li>Using CALL SYMPUT with DATA Step Expressions </li></ul><ul><li>       call symput(' due ', trim(left( put(fee*(total-paidup),dollar8.) ))); </li></ul><ul><li>Creating Multiple Macro Variables with CALL SYMPUT </li></ul><ul><li>       call symput(course_code, trim(course_title)); </li></ul><ul><li>       call symput('teach'||left(course_number),                    trim(teacher)); </li></ul><ul><li>When you use a DATA step expression as the second argument, its current value is evaluated according to the following rules: </li></ul><ul><li>Numeric expressions are a utomatically converted to character constants, using the BEST12. format. </li></ul><ul><li>The resulting value can be up to 32767 characters long. </li></ul><ul><li>Any leading or trailing blanks that are part of the expression are stored in the macro variable. </li></ul>11/13/09 SAS Techies 2009
  28. 28. <ul><li>The INTO clause in a SELECT statement enables you to create or update macro variables. </li></ul><ul><ul><li>proc sql NOPRINT ;     </li></ul></ul><ul><ul><li>select course_code, location, begin_date format=mmddyy10.        </li></ul></ul><ul><ul><li>into :crsid1-:crsid3, </li></ul></ul><ul><ul><li>       :place1-:place3, </li></ul></ul><ul><ul><li>       :date1-:date3 </li></ul></ul><ul><ul><li>from sasuser.schedule </li></ul></ul><ul><ul><li>where year(begin_date)=2002 </li></ul></ul><ul><ul><li>order by begin_date;     quit; </li></ul></ul><ul><ul><li>the INTO clause cannot be used when you create a table or a view. </li></ul></ul><ul><ul><li>Most common usage - </li></ul></ul><ul><ul><li>select count(*) into :numrows </li></ul></ul><ul><ul><li>select course_code, </li></ul></ul><ul><ul><li>location, </li></ul></ul><ul><ul><li>begin_date format=mmddyy10. </li></ul></ul><ul><ul><li>   into :crsid1-:crsid &numrows,   </li></ul></ul><ul><ul><li>         :place1-:place &numrows </li></ul></ul><ul><ul><li>SELECT column1 INTO : macro-variable-1 SEPARATED BY ' delimiter1 ' </li></ul></ul>11/13/09 SAS Techies 2009
  29. 29. <ul><li>SYMGET (‘ macro-variable’ ) </li></ul><ul><li>%let crsid=C003;     </li></ul><ul><li>proc sql; </li></ul><ul><li>create view subcrsid as </li></ul><ul><li>select student_name,student_company,paid </li></ul><ul><li>From sasuser.all </li></ul><ul><li>where course_code= symget('crsid') ; </li></ul><ul><li>    quit; </li></ul>       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. 30. <ul><li>%MACRO macro-name ; </li></ul><ul><li>text </li></ul><ul><li>%MEND < macro-name >; </li></ul><ul><li>where </li></ul><ul><li>macro-name names the macro. </li></ul><ul><li>The value of macro-name can be any valid SAS name that is not a reserved word in the SAS macro facility. </li></ul><ul><li>text can be </li></ul><ul><ul><li>constant text, possibly including SAS data set names, SAS variable names, or SAS statements </li></ul></ul><ul><ul><li>macro variables, macro functions, or macro program statements </li></ul></ul><ul><ul><li>any combination of the above. </li></ul></ul><ul><li>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. </li></ul><ul><li>A macro call </li></ul><ul><ul><li>is specified by placing a percent sign (%) before the name of the macro </li></ul></ul><ul><ul><li>can be made anywhere in a program except within the data lines of a DATALINES statement (similar to a macro variable reference) </li></ul></ul><ul><ul><li>requires no semicolon because it is not a SAS statement. </li></ul></ul>11/13/09 SAS Techies 2009
  31. 31. <ul><li>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 . </li></ul><ul><li>When the macro processor receives %macro-name , it </li></ul><ul><ul><li>searches the designated SAS catalog ( Work.Sasmacr by default) for an entry named Macro-name .Macro . </li></ul></ul><ul><ul><li>executes compiled macro language statements within Macro-name . </li></ul></ul><ul><ul><li>sends any remaining text in Macro-name to the input stack for word scanning. </li></ul></ul><ul><ul><li>suspends macro execution when the SAS compiler receives a global SAS statement or when it encounters a SAS step boundary. </li></ul></ul><ul><ul><li>resumes execution of macro language statements after the SAS code executes. </li></ul></ul>11/13/09 SAS Techies 2009
  32. 32. <ul><li>Symbolgen option – Macros resolved values </li></ul><ul><li>The MPRINT option - the text that is sent to the SAS compiler as a result of macro execution is printed in the SAS log. </li></ul><ul><li>The MLOGIC Option – </li></ul><ul><li>When the MLOGIC system option is in effect, the information that is displayed in SAS log messages includes </li></ul><ul><ul><li>the beginning of macro execution </li></ul></ul><ul><ul><li>the results of arithmetic and logical macro operations </li></ul></ul><ul><ul><li>the end of macro execution. </li></ul></ul><ul><li>All these options are used in Code Development phase and turned off in Production/Testing Phases….Required….display passwords….extraneous log files… </li></ul>11/13/09 SAS Techies 2009
  33. 33. <ul><li>%macro prtlast;    </li></ul><ul><li>proc print data=&syslast(obs=5);   </li></ul><ul><li>title &quot;Listing of &syslast data set&quot;;    </li></ul><ul><li>run; </li></ul><ul><li>%mend; </li></ul><ul><li>    </li></ul><ul><li>data sales; </li></ul><ul><li>price_code=1;     </li></ul><ul><li>run; </li></ul><ul><li>options mprint;     </li></ul><ul><li>%prtlast </li></ul>11/13/09 SAS Techies 2009
  34. 34. <ul><li>%macro printdsn (dsn,vars) ; </li></ul><ul><li>     proc print data=&dsn; </li></ul><ul><li>      var &vars; </li></ul><ul><li>      title &quot;Listing of %upcase(&dsn) data set&quot;;          </li></ul><ul><li>run;      </li></ul><ul><li>%mend; </li></ul><ul><li>To substitute a null value for one or more positional parameters, use commas as placeholders for the omitted values, as follows: </li></ul><ul><li>%printdsn(,course_code course_title days) </li></ul><ul><li>When you include positional parameters in a macro definition, a local macro variable is automatically created for each parameter when you call the macro. </li></ul><ul><li>To define macros that include positional parameters , you list the names of macro variables in the %MACRO statement of the macro definition. </li></ul><ul><li>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. </li></ul>11/13/09 SAS Techies 2009
  35. 35. <ul><li>%macro printdsn (dsn= </li></ul><ul><li>sasuser.courses,vars=course_code </li></ul><ul><li>                     course_title days) ; </li></ul><ul><li>  proc print data=&dsn;   </li></ul><ul><li>   var &vars; </li></ul><ul><li>  title &quot;Listing of %upcase(&dsn) data set&quot;; </li></ul><ul><li>  run;      </li></ul><ul><li>%mend; </li></ul><ul><li>%printdsn(dsn=sasuser.schedule, vars=teacher               course_code begin_date) </li></ul><ul><li>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. </li></ul><ul><li>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 </li></ul>11/13/09 SAS Techies 2009
  36. 36. <ul><li>%macro printdsn( dsn, vars=course_title course_code days ); </li></ul><ul><li>proc print data=&dsn;   </li></ul><ul><li>var &vars; </li></ul><ul><li>title &quot;Listing of %upcase(&dsn) data set&quot;; </li></ul><ul><li>run; </li></ul><ul><li>%mend; </li></ul><ul><li>when you call a macro that includes a mixed parameter list, you must list the positional values before any keyword values , as follows: </li></ul><ul><li>% macro-name ( value-1<,...,value-n>,                 keyword-1=value-1<,...,keyword-n=value-n> ) </li></ul>11/13/09 SAS Techies 2009
  37. 37. <ul><li>%macro printz/ parmbuff ;   </li></ul><ul><li>%put Syspbuff contains: &syspbuff; </li></ul><ul><li>  %let num=1;   </li></ul><ul><li>  %let dsname=%scan( &syspbuff ,&num,’,’); </li></ul><ul><li>%do %while(&dsname ne _ ); </li></ul><ul><li>proc print data=sasuser.&dsname; </li></ul><ul><li>run; </li></ul><ul><li>%let num=%eval(&num+1); </li></ul><ul><li>%let dsname=%scan( &syspbuff ,&num,’,’); </li></ul><ul><li>%end;      </li></ul><ul><li>%mend printz; </li></ul><ul><li>%printz (dsn1,dsn2, dsn3) </li></ul><ul><li>Parmbuff option allows to send varying parameter calls to macros. </li></ul><ul><li>The automatic macro variable SYSPBUFF is used to capture those variable values.display the parameters that are specified in the macro call. </li></ul>11/13/09 SAS Techies 2009
  38. 38. <ul><li>You can create a global macro variable with </li></ul><ul><ul><li>a %LET statement (used outside a macro definition) </li></ul></ul><ul><ul><li>a DATA step that contains a SYMPUT routine </li></ul></ul><ul><ul><li>a SELECT statement that contains an INTO clause in PROC SQL </li></ul></ul><ul><ul><li>a %GLOBAL statement. </li></ul></ul><ul><li>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. </li></ul><ul><li>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 </li></ul><ul><ul><li>are available anytime during the session </li></ul></ul><ul><ul><li>can be created by a user </li></ul></ul><ul><ul><li>have values that can be changed during the session (except for some automatic macro variables). </li></ul></ul>11/13/09 SAS Techies 2009
  39. 39. <ul><li>You can create local macro variables with - </li></ul><ul><ul><li>parameters in a macro definition </li></ul></ul><ul><ul><li>a %LET statement within a macro definition </li></ul></ul><ul><ul><li>a DATA step that contains a SYMPUT routine within a macro definition </li></ul></ul><ul><ul><li>a SELECT statement that contains an INTO clause in PROC SQL within a macro definition </li></ul></ul><ul><ul><li>a %LOCAL statement. </li></ul></ul><ul><li>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. </li></ul><ul><li>The local symbol table is deleted when the macro finishes execution. </li></ul><ul><li>That is, the local symbol table exists only while the macro executes. </li></ul><ul><li>The local symbol table contains macro variables that can be </li></ul><ul><ul><li>created and initialized at macro invocation (that is, by parameters) </li></ul></ul><ul><ul><li>created or updated during macro execution </li></ul></ul><ul><ul><li>referenced anywhere within the macro. </li></ul></ul>11/13/09 SAS Techies 2009
  40. 40. <ul><li>%let dsn=sasuser.courses;       </li></ul><ul><li>%macro printdsn;    </li></ul><ul><li>     %local dsn;    </li></ul><ul><li>     %let dsn=sasuser.register; </li></ul><ul><li>       %put The value of DSN inside Printdsn is &dsn; </li></ul><ul><li>    %mend;   </li></ul><ul><li>    %printdsn     </li></ul><ul><li>%put The value of DSN outside Printdsn is &dsn; </li></ul>11/13/09 SAS Techies 2009
  41. 41. <ul><li>%macro outer;   </li></ul><ul><li>   %local variX; </li></ul><ul><li>    %let variX=one; </li></ul><ul><li>     %inner     </li></ul><ul><li>%mend outer; </li></ul><ul><li>    %macro inner; </li></ul><ul><li>      %local variY; </li></ul><ul><li>       %let variY=&variX;   </li></ul><ul><li>   %mend inner; </li></ul><ul><li>%let variX=zero;    </li></ul><ul><li>%outer </li></ul><ul><li>Multiple local symbol tables can exist concurrently during macro execution if you have nested macros . </li></ul><ul><li>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. </li></ul><ul><li>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. </li></ul>11/13/09 SAS Techies 2009
  42. 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. 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. 44. <ul><li>If expression resolves to zero, then it is false and the %THEN text is not processed (the optional %ELSE text is processed instead). </li></ul><ul><li>%macro choice(status); </li></ul><ul><li>data fees; </li></ul><ul><li>set sasuser.all; </li></ul><ul><li>%if &status=PAID %then %do; </li></ul><ul><li>       where paid='Y'; </li></ul><ul><li>        keep student_name course_code begin_date totalfee; </li></ul><ul><li>       %end;    </li></ul><ul><li>%else %do; </li></ul><ul><li>        where paid='N'; </li></ul><ul><li>       keep student_name course_code </li></ul><ul><li>       begin_date totalfee latechg;   </li></ul><ul><li>       latechg=fee*.10;    </li></ul><ul><li>        %end; </li></ul><ul><li>Run; </li></ul><ul><li>%mend choice; </li></ul><ul><li>%choice(PAID); </li></ul>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. 45. <ul><li>data _null_; </li></ul><ul><li>set sasuser.schedule end=no_more; </li></ul><ul><li>call symput('teach'||left(_n_),(trim(teacher)));        </li></ul><ul><li>if no_more then call symput('count',_n_); </li></ul><ul><li>run; </li></ul><ul><li>%macro putloop; </li></ul><ul><li>     %local i; </li></ul><ul><li>       %do i=1 %to &count; </li></ul><ul><li>          %put TEACH&i is &&teach&i; </li></ul><ul><li>       %end; </li></ul><ul><li>%mend putloop; </li></ul><ul><li>%putloop </li></ul><ul><li>With the iterative %DO statement you can repeatedly </li></ul><ul><ul><li>execute macro programming code </li></ul></ul><ul><ul><li>generate SAS code. </li></ul></ul><ul><li>%DO and %END statements are valid only inside a macro definition </li></ul>11/13/09 SAS Techies 2009
  46. 46. <ul><li>The %EVAL function </li></ul><ul><ul><li>translates integer strings and hexadecimal strings to integers. </li></ul></ul><ul><ul><li>translates tokens representing arithmetic, comparison, and logical operators to macro-level operators. </li></ul></ul><ul><ul><li>performs arithmetic and logical operations. </li></ul></ul><ul><li>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. </li></ul><ul><li>The %EVAL function does not convert the following to numeric values: </li></ul><ul><ul><li>numeric strings that contain a period or E-notation </li></ul></ul><ul><ul><li>SAS date and time constants. </li></ul></ul><ul><li>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. </li></ul>11/13/09 SAS Techies 2009
  47. 47. <ul><li>Code - c:sasfilesprtlast.sas </li></ul><ul><li>   %macro prtlast; </li></ul><ul><li>    %if &syslast ne _NULL_ %then %do; </li></ul><ul><li>      proc print data=&syslast(obs=5);   </li></ul><ul><li>      title &quot;Listing of &syslast data set&quot;; </li></ul><ul><li>      run;        </li></ul><ul><li>%end; </li></ul><ul><li>    %else </li></ul><ul><li>   %put No data set has been created yet.; </li></ul><ul><li>    %mend; </li></ul><ul><li>Your Program </li></ul><ul><li>%include 'c:sasfilesprtlast.sas' /source2; </li></ul><ul><li>proc sort data=sasuser.courses out=bydays; </li></ul><ul><li>by days; </li></ul><ul><li>run; </li></ul><ul><li>%prtlast </li></ul><ul><li>use the %INCLUDE statement to insert the statements that are stored in the external file into a program. </li></ul><ul><li>By storing your macro program externally and using the %INCLUDE statement, you gain several advantages over using session-compiled macros. </li></ul><ul><ul><li>The source code for the macro definition does not need to be part of your program. </li></ul></ul><ul><ul><li>A single copy of a macro definition can be shared by many programs. </li></ul></ul><ul><ul><li>Macro definitions in external files are easily viewed and edited with any text editor. </li></ul></ul><ul><ul><li>No special SAS system options are required in order to access a macro definition that is stored in an external file. </li></ul></ul>11/13/09 SAS Techies 2009
  48. 48. <ul><li>OPTIONS MAUTOSOURCE | NOMAUTOSOURCE ; </li></ul><ul><li>OPTIONS SASAUTOS= ( library-1,...,library-n) ; </li></ul><ul><li>Eg: </li></ul><ul><li>Libname sasmacs “'c:mysasfiles'”; </li></ul><ul><li>options mautosource sasautos=(sasmacs,sasautos);     </li></ul><ul><li>%prtlast </li></ul><ul><li>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 . </li></ul><ul><li>When you submit a call to that macro, </li></ul><ul><ul><li>the macro processor searches the autocall library for the macro </li></ul></ul><ul><ul><li>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 ) </li></ul></ul><ul><ul><li>the macro is executed. </li></ul></ul>11/13/09 SAS Techies 2009
  49. 49. <ul><li>OPTIONS MSTORED | NOMSTORED ; </li></ul><ul><li>OPTIONS SASMSTORE= libref ; </li></ul><ul><li>%MACRO macro-name < (parameter-list) > / STORE </li></ul><ul><li>< DES= 'description' > ; </li></ul><ul><li>text </li></ul><ul><li>%MEND < macro-name > ; </li></ul><ul><li>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. </li></ul><ul><li>There are several restrictions on stored compiled macros. </li></ul><ul><ul><li>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. </li></ul></ul><ul><ul><li>You cannot copy stored compiled macros across operating systems. You must copy the source program and re-create the stored compiled macro. </li></ul></ul><ul><ul><li>The source cannot be re-created from the compiled macro. So save the original source program. </li></ul></ul>11/13/09 SAS Techies 2009
  50. 50. 11/13/09 SAS Techies 2009
  51. 51. <ul><li>The %SYMDEL statement enables you to delete a macro variable from the global symbol table during a SAS session. </li></ul><ul><li>You can call a macro within a macro definition. That is, you can nest macros. </li></ul><ul><li>When a nested macro is called, multiple local symbol tables can exist. </li></ul><ul><li>The MPRINTNEST and MLOGICNEST options provide nesting information in the messages that are written to the SAS log for the MPRINT and MLOGIC options. </li></ul><ul><li>You cannot nest functions within %SYSFUNC, but you can use a %SYSFUNC for each function that you need, as shown in this </li></ul><ul><li>eg: title &quot;Report Produced on %sysfunc(left(%sysfunc put(today(),worddate.)))&quot;; </li></ul>11/13/09 SAS Techies 2009

×