SAS Macro SAS Training Courses By Amadeus Software Ltd
AMADEUS SOFTWARE LIMITED SAS TRAINING Amadeus have been delivering SAS Training since 1989 and our aim is to provide you with best quality SAS training where, when and how you choose. Delivery Options Available: Public Training On-Site Training On-Demand Training Types of Training Available: Training Courses: Classroom based with a mixture of demonstration sessions and workshop sessions. Each delegate receives a copy of course material which can be used as reference material after the class. Workshops: Classroom based with practical sessions. There will be very little in the way of lecturing; delegates will be expected to actively contribute during the workshop. Written material will be provided to delegates, this material will not be a textbook but a record of the practical steps followed during the workshop. On-Demand: Amadeus On-Demand training is delivered through a web browser to any computer or device with internet access. Training is recorded and conducted by our most experienced instructors using in-depth examples, video demonstrations and animations. RECOMMENDED TRAINING CURRICULUM PATH CONTACT Amadeus Software Limited Mulberry House, 9 Church Green, Witney, Oxon, OX28 4AZ, England. Tel: +44 (0)1993 848010 Email: info@amadeus.co.uk Web Site: www.amadeus.co.uk
Credits Credits This SAS Software training course was written by Staff of Amadeus Software Ltd. Version 6.3 Copyright Notice Copyright 2013 by Amadeus Software Ltd. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying or otherwise, without prior permission of the publisher, Amadeus Software Ltd, Witney, Oxfordshire, England. Trademark Notice The Amadeus logo is a trademark of Amadeus Software Ltd, Witney, Oxfordshire, England. SAS and all other SAS Institute Inc. product or service names are registered trademarks or trademarks of SAS Institute Inc. in the USA and other countries. indicates USA registration All other trademarks recognised. Disclaimer These course notes are intended to supplement documentation supplied by SAS Institute, and not to replace it. Where SAS syntax is given here, it may not include all possible options. Similarly, lists of statements, functions, formats, macro variables and other SAS features given here are not intended to be comprehensive. For complete and up-to-date information, please refer to the SAS Institute documentation..
Table of Contents Table of Contents M1 INTRODUCTION... Common Coding Tasks... Example 1... Example 2... Example 3... Example 4 (Optional - SAS/Graph users)... General Strategy... Workshop Session... M2 MACRO VARIABLES...... Automatic Macro Variables... Automatic System Macro Variables... Operating System Dependency... Determining the Values of Macro Variables... Using SASHELP.VMACRO... Using %PUT Statement... Creating User-Defined Macro Variables... %LET Statement... Macro Functions... Optional - SAS/Connect Software Users... Resolution Considerations... Limiting the Extent of Resolution... Multi - Pass Resolution... Rules for Dealing with Multiple Ampersands... Debugging Option - SYMBOLGEN... Macro Variables vs. DATA Step Variables... Workshop Session... M3 MACROS... Definition of a Macro... Macro Definition... Debugging Option MCOMPILENOTE... The Macro Call... Debugging Option MPRINT... Passing Parameters... Positional Parameters... Keyword Parameters... Combination of Positional and Keyword Parameters... Varying Number of Parameters... 1
Table of Contents Compilation and Execution Phases... Deleting a Compiled Macro... Other Macro Forms (Optional)... Workshop Session... M4 BEHIND THE SCENES... Symbol Tables Rules... Example 1... Example 2... Example 3... Example 4... Example 5... Example 6... Deleting Macro Variables... Nested Macros... Additional Debugging Options... GLOBAL and LOCAL Variables... Problem 1... Solution to Problem 1... Problem 2... Solution to Problem 2... Creating READONLY Macro Variables... Determining Whether a Macro Variable Exists... Workshop Session... M5 MACRO PROGRAMMING... Directing Macro Execution... Macro Statements... Macro Comments... Conditional Statements... Debugging Option MLOGIC... AND/OR Logical Operators... Evaluating an Item Against a List of Items... Iteration... Conditional Termination of Macro Flow... %RETURN... %ABORT... String Manipulation... %LENGTH... %UPCASE... %SUBSTR... %INDEX... %SCAN... %SYSFUNC, %QSYSFUNC and %SYSCALL... Example 1 Numeric DATA Step Functions... Example 2 Formatting the Text in a TITLE Statement... Example 3 Check for the Existence of a SAS Data Set... Example 4 Formatting the Date in a TITLE Statement... 2
Table of Contents Example 5 Moving a Date Forward... Workshop Session... M6 THE DATA STEP INTERFACE... Functions and Call Routines... SYMGET... Dynamic Change to the Macro Variable Name... Call SYMPUT and Call SYMPUTX... Syntax... Combinations of Form... Example 1 - Data Dependent Titles... Example 2 - Triggering a PROC Based on a DATA Step Value... Example 3 - Sub-Setting a Data Set... Creating a Macro Variable from Proc SQL... Workshop Session... M7 HANDLING SPECIAL CHARACTERS...... Numeric Evaluations... Explicit Evaluation... Numeric Comparison... Implied Evaluation... Automatic Evaluation... to Quoting Functions... Characters and Operators that Can Be Masked... Why are Quoting Functions Called Quoting Functions?... Rescan or No Rescan?... Compile Time or Execution Time?... Example 1 - Using Quoting Functions to Mask Semicolons at Compilation Time... Example 2 - Using Quoting Functions to Mask % and & Characters at Compilation Time... Example 3 - Using Quoting Functions to Mask Mnemonic Operators at Compilation Time... Example 4 - Using Quoting Functions to Mask Mnemonic Operators at Execution Time... Example 5 - Using Quoting Functions to Work with Unbalanced Quotation Marks or Parentheses at Compilation Time... Example 6 - Using Quoting functions to work with Unbalanced Quotation Marks at Compilation and Execution Time... Built-in Quoting... Summary... Comparison of Quoting Functions... Workshop Session... M8 WORKING WITH MACROS... Using the %INCLUDE Statement... The Autocall Library... The Autocall Facility... Aggregate Storage Locations... Enabling Autocall... 3
Table of Contents The Supplied Library... The Stored Compiled Macro Facility... Storing Macros as Catalog Source Entries (Optional)... How SAS Resolves Macro Calls... Writing Successful Macros... Modularity... Referencing Environments... Design... Code Layout... Robustness... Documentation... Efficiency... Maintenance... Workshop Session... WORKSHOP SOLUTIONS... M1 Exercise 1... M1 Exercise 2... M1 Exercise 3... M1 Exercise 4... M1 Exercise 5... M2 Exercise 1... M2 Exercise 2... M2 Exercise 3... M2 Exercise 4... M2 Exercise 5... M2 Exercise 6... M2 Exercise 7... M2 Exercise 8... M3 Exercise 1... M3 Exercise 2... M3 Exercise 3... M3 Exercise 4... M3 Exercise 5... M4 Exercise 1... M4 Exercise 2... M4 Exercise 3... M5 Exercise 1... M5 Exercise 2... M5 Exercise 3... M5 Exercise 4... M5 Exercise 5... M5 Exercise 6... M5 Exercise 7... M6 Exercise 1... M6 Exercise 2... M6 Exercise 3... M6 Exercise 4... M6 Exercise 5... M6 Exercise 6... M6 Exercise 7... M7 Exercise 1... M7 Exercise 2... M7 Exercise 3... M7 Exercise 4... 4
Table of Contents M7 Exercise 5... M7 Exercise 6... M7 Exercise 7... M8... 5
Table of Contents 6
M1 Common Coding Tasks General Strategy Workshop Session 1-1
1-2
Common Coding Tasks Those with some experience in SAS DATA and procedure step programming may have come across several classic problems during the course of their work. Example 1 How would you include the current date in the title of a report? In order to do so, you would have to be able to write a TITLE statement that could somehow extract the current date from the system clock. Here is a first attempt at a variable title statement: And not surprisingly, the output starts as: Not very successful! 1-3
The macro solution: You can use several automatic macro variables. Automatic implies that the macro variable is available to you when you are running SAS programs. Example 2 As a second example, suppose you want to execute some code conditionally, based upon the day of the week. You may want to execute different steps dependent upon the results of tests. The code below will NOT work because step types are being mixed: 1-4
You cannot mix DATA steps and PROC steps in a SAS program. They have to be separate and only the macro language can pass values from one step to another. 1-5
For example: 1-6
Example 3 In this third example, suppose you have a monthly series of twelve files all to be run with the same report. In this case our 'wrong' attempt may look something like: Here we are assuming our twelve SAS data sets are called MDATA.DS_1 to MDATA.DS_12. This again, will not work because of the attempt to mix steps. We could write 12 individual Proc TABULATE steps however. This alternative solution creates a bundle of code called a macro which will pass a different value to the Proc TABULATE code each time round the loop. 1-7
Example 4 (Optional - SAS/Graph users) The fourth example again shows data dependency. Suppose we wish to plot some data and place across it a reference line whose value is dependent on the data. The data set used in the next example is the EPIDEMIC data set. This contains the number of influenza cases reported per week for five age ranges of the population (categories A to E). For category A we wish to plot the number of reported cases against the date (in this case a running week number), but to place across the plot a reference line referring to the average number of cases reported over the period. Our attempt may look like this: Here the intermediate SAS data set called NEWDATA contains the variable AVNUM for all observations, but unfortunately a syntax error results as the VREF option demands an explicit value. 1-8
Here is the syntax error caused by using a variable name with the VREF option: Macro again can offer us a solution as a macro variable can resolve to an explicit value. 1-9
1-10
General Strategy By now you will have noticed the key symbols within the macro language are the ampersand (&) and the percent sign (%). Before we look at the effect of these two symbols, let us consider the progress of a normal DATA step program. This program has one step; a DATA step. The SAS Supervisor places all of these statements in a program input stack, takes one word at a time from the stack and passes them to the SAS compiler or procedure parser (if the step is a proc). At the end of the statement when a semi-colon is reached the statement is checked for syntax. At a step boundary, this process is halted and the step is compiled or parsed, then executed. TOP OF STACK data defines a step boundary run defines a step boundary data new_demog; set mdata.demog; if age > 35 then newsal=salary*1.05; else newsal=salary*1.01; run; 1-11
A SAS program is simply a sequence of DATA and PROC steps Each step is delimited by the keywords such as: DATA PROC RUN QUIT ENDSAS A 'word' (or 'token') at a time is transferred to the DATA step compiler or procedure parser. TOP OF STACK data defines a step boundary run defines a step boundary data new_demog; set mdata.demog; if age > 35 then newsal=salary*1.05; else newsal=salary*1.01; run; SAS SUPERVISOR SAS Compiler or Procedure Parser data First Token passed through data new_demog Next Token passed through data new_demog; Checked for Syntax 1-12
TOP OF STACK data defines a step boundary run defines a step boundary data new_demog; set mdata.demog; if age > 35 then newsal=salary*1.05; else newsal=salary*1.01; run; SAS SUPERVISOR SAS Compiler or Procedure Parser data new_demog; set and so on, until the RUN; step boundary is found. Upon a step boundary, the SAS Supervisor suspends processing the SAS statements and the completed step is compiled (or parsed in the case of a procedure) and then executed. Each step independently compiles (parses) and then executes. 1-13
A SAS program is, and can only be, a series of DATA and PROC steps plus any global statements. The role of Macro is simply to generate code that is to be put on top of the program input stack. TOP OF STACK &sysdate"; proc print data=mdata.policies; var polnum policy; where type='life'; run; SAS SUPERVISOR MACRO SAS Compiler or Procedure Parser title "Job run on The presence of the & followed by a non-blank character triggers the macro facility. The token is passed to the macro facility, which substitutes a value on the input stack. 1-14
The value of the macro variable is retrieved by the macro facility and placed on the input stack: TOP OF STACK 26JUN17"; proc print data=mdata.policies; var polnum policy; where type='life'; run; SAS SUPERVISOR MACRO SAS Compiler or Procedure Parser title "Job run on Whereupon, the replaced code is treated as normal: TOP OF STACK "; proc print data=mdata.policies; var polnum policy; where type='life'; run; SAS SUPERVISOR MACRO SAS Compiler or Procedure Parser title "Job run on 26JUN17 1-15
So, the SAS macro facility is concerned with extending and customising the SAS language. It gives users the ability to: Generate code dynamically; Handle text string substitution within code; Enable repeated execution of code bundles; Use conditional logic to execute code. It should be stressed that the SAS macro facility will not enable SAS code to run quicker, but rather produce SAS programs that are potentially re-usable, dynamic and can be maintained more easily. 1-16