SAS Macro. SAS Training Courses. Amadeus Software Ltd

Similar documents
Introduction. Getting Started with the Macro Facility CHAPTER 1

SAS Macro Language: Reference

Base and Advance SAS

Acknowledgments xi Preface xiii About the Author xv About This Book xvii New in the Macro Language xxi

Understanding the Concepts and Features of Macro Programming 1

CHAPTER 7 Using Other SAS Software Products

Going Under the Hood: How Does the Macro Processor Really Work?

Journey to the center of the earth Deep understanding of SAS language processing mechanism Di Chen, SAS Beijing R&D, Beijing, China

Introduction to the SAS Macro Facility

More About SAS Macros

SAS CURRICULUM. BASE SAS Introduction

Advanced Macro Topics Steven First, Systems Seminar Consultants, Madison, WI

Basic Macro Processing Prepared by Destiny Corporation

Surviving the SAS Macro Jungle by Using Your Own Programming Toolkit Kevin Russell, SAS Institute Inc., Cary, North Carolina

Foundations and Fundamentals. SAS System Options: The True Heroes of Macro Debugging Kevin Russell and Russ Tyndall, SAS Institute Inc.

DSCI 325: Handout 15 Introduction to SAS Macro Programming Spring 2017

title1 "Visits at &string1"; proc print data=hospitalvisits; where sitecode="&string1";

SAS Certification Handout #11: Adv. Prog. Ch. 9-10

An Introduction to SAS Macros

Sandra Hendren Health Data Institute

SAS Macro Dynamics: from Simple Basics to Powerful Invocations Rick Andrews, Office of Research, Development, and Information, Baltimore, MD

Macro Basics. Introduction. Defining and Using Macro Variables. Defining and Using Macros. Macro Parameters. Part 1. Chapter 1. Chapter 2.

My Enterprise Guide David Shannon, Amadeus Software Limited, UK

A Time Saver for All: A SAS Toolbox Philip Jou, Baylor University, Waco, TX

SAS 9 Programming Enhancements Marje Fecht, Prowerk Consulting Ltd Mississauga, Ontario, Canada

The Ins and Outs of %IF

QUEST Procedure Reference

Unlock SAS Code Automation with the Power of Macros

SAS Macro Dynamics - From Simple Basics to Powerful Invocations Rick Andrews, Office of the Actuary, CMS, Baltimore, MD

Macro Internals for the User Developer s Overview. Susan O Connor, SAS Institute Inc., Cary, NC

Simplifying Your %DO Loop with CALL EXECUTE Arthur Li, City of Hope National Medical Center, Duarte, CA

Macro Bugs - How to Create, Avoid and Destroy Them Ian Whitlock, Kennett Square, PA

Efficiency Programming with Macro Variable Arrays

APPENDIX 4 Migrating from QMF to SAS/ ASSIST Software. Each of these steps can be executed independently.

&&&, ;;, and Other Hieroglyphics Advanced Macro Topics Chris Yindra, C. Y. Training Associates

GET A GRIP ON MACROS IN JUST 50 MINUTES! Arthur Li, City of Hope Comprehensive Cancer Center, Duarte, CA

SAS Macro Programming for Beginners

AN INTRODUCTION TO MACRO VARIABLES AND MACRO PROGRAMS Mike Zdeb, School of Public Health

An Animated Guide: An Introduction to SAS Macro Quoting Russ Lavery Bryn Mawr, PA

SURVIVING THE SAS MACRO JUNGLE BY USING YOUR OWN PROGRAMMING TOOLKIT

Program Validation: Logging the Log

HOW TO DEVELOP A SAS/AF APPLICATION

MOBILE MACROS GET UP TO SPEED SOMEWHERE NEW FAST Author: Patricia Hettinger, Data Analyst Consultant Oakbrook Terrace, IL

SAS Online Training: Course contents: Agenda:

Tales from the Help Desk 5: Yet More Solutions for Common SAS Mistakes Bruce Gilsen, Federal Reserve Board

Using Data Transfer Services

A Tutorial on the SAS Macro Language

STATION

An Introduction to Macros Deb Cassidy

Paper ###-YYYY. SAS Enterprise Guide: A Revolutionary Tool! Jennifer First, Systems Seminar Consultants, Madison, WI

Tired of CALL EXECUTE? Try DOSUBL

The SAS Interface to REXX

Customising SAS OQ to Provide Business Specific Testing of SAS Installations and Updates

Jeff Phillips, ARC Professional Services Group Veronica Walgamotte, ARC Professional Services Group Derek Drummond, ARC Professional Services Group

INTRODUCTION TO SAS HOW SAS WORKS READING RAW DATA INTO SAS

BASICS BEFORE STARTING SAS DATAWAREHOSING Concepts What is ETL ETL Concepts What is OLAP SAS. What is SAS History of SAS Modules available SAS

COMPILER DESIGN LECTURE NOTES

Functions vs. Macros: A Comparison and Summary

Seminar Series: CTSI Presents

SAS Macro Language 1: Essentials. Course Notes

No, it's not magic: De-mystifying the SAS Macro Facility Jay A. Jaffe, PhD

Your Own SAS Macros Are as Powerful as You Are Ingenious

Exploring the SAS Macro Function %SYSFUNC

SAS Programming Techniques for Manipulating Metadata on the Database Level Chris Speck, PAREXEL International, Durham, NC

Contents. About This Book...1

SAS Institute Exam A SAS Advanced Programming Version: 6.0 [ Total Questions: 184 ]

Extending the Scope of Custom Transformations

Chapter 7 File Access. Chapter Table of Contents

%MISSING: A SAS Macro to Report Missing Value Percentages for a Multi-Year Multi-File Information System

Why & How To Use SAS Macro Language: Easy Ways To Get More Value & Power from Your SAS Software Tools


Using Macro Functions

Macro Quoting: Which Function Should We Use? Pengfei Guo, MSD R&D (China) Co., Ltd., Shanghai, China

Macros from Beginning to Mend A Simple and Practical Approach to the SAS Macro Facility

Paper 149 JAY A. JAFFE

PLA YING WITH MACROS: TAKE THE WORK OUT OF LEARNING TO DO MACROS. Arthur L. Carpenter

New Macro Features Added in SAS 9.3 and SAS 9.4

Contents. Overview How SAS processes programs Compilation phase Execution phase Debugging a DATA step Testing your programs

Files Arriving at an Inconvenient Time? Let SAS Process Your Files with FILEEXIST While You Sleep

Get Started Writing SAS Macros Luisa Hartman, Jane Liao, Merck Sharp & Dohme Corp.

Arthur L. Carpenter California Occidental Consultants, Oceanside, California

Inspiring P3O Training

DATA Step Debugger APPENDIX 3

SAS System Powers Web Measurement Solution at U S WEST

Storing and Reusing Macros

COMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou

SAS Macro Programming Tips and Techniques

An Introduction to SAS/SHARE, By Example

SAS/FSP 9.2. Procedures Guide

PRINCIPLES OF COMPILER DESIGN UNIT I INTRODUCTION TO COMPILING

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

Vijeo Citect Customization and Design Study Guide

Unravelling the Knot of Ampersands

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

SAS Macro Design Issues Ian Whitlock, Westat

SAS Business Rules Manager 1.2

Chapter 1. Introduction. 1.1 More about SQL More about This Book 5

Lecture 1 Getting Started with SAS

Submitting SAS Code On The Side

Lesson 1: Writing Your First JavaScript

Transcription:

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