sas slides 12 : macros

51
SAS Techies [email protected] http://www.sastechies.com

Upload: sastechies

Post on 16-Nov-2014

7.706 views

Category:

Documents


5 download

DESCRIPTION

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

TRANSCRIPT

Page 1: SAS Slides 12 : Macros

SAS [email protected]

http://www.sastechies.com

Page 2: SAS Slides 12 : Macros

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

2

TLG’s

04/08/23SAS Techies 2009

Page 3: SAS Slides 12 : Macros

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

3

title "Temporary Employees for 1999"; data hrd.temp1999; 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

04/08/23SAS Techies 2009

Page 4: SAS Slides 12 : Macros

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.

4

%let yr=1999;title "Temporary Employees for &yr"; data hrd.temp&yr; set hrd.temp; if year(enddate)= &yr;

04/08/23SAS Techies 2009

Page 5: SAS Slides 12 : Macros

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

5

footnote "Report Run on &sysdate";

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

footnote ‘Report Run on &sysdate’;

footnote “Report Run on &sysdate”;

04/08/23SAS Techies 2009

Page 6: SAS Slides 12 : Macros

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.

6

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

04/08/23SAS Techies 2009

Page 7: SAS Slides 12 : Macros

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

7

%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;

04/08/23SAS Techies 2009

Page 8: SAS Slides 12 : Macros

%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.

804/08/23SAS Techies 2009

Page 9: SAS Slides 12 : Macros

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;

9

Global Symbol Table

SYSTIME 09.47 automaticvariablesSYSVER 8.01

CITY Dallas user-definedvariables

DATE 05JAN2000

AMOUNT 975

04/08/23SAS Techies 2009

Page 10: SAS Slides 12 : Macros

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.

1004/08/23SAS Techies 2009

Page 11: SAS Slides 12 : Macros

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.

1104/08/23SAS Techies 2009

Page 12: SAS Slides 12 : Macros

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:

* / +  -  **  ;  $  (  )  .  &  %

12

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.

04/08/23SAS Techies 2009

Page 13: SAS Slides 12 : Macros

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.

04/08/23SAS Techies 2009

Page 14: SAS Slides 12 : Macros

1404/08/23SAS Techies 2009

Page 15: SAS Slides 12 : Macros

1504/08/23SAS Techies 2009

Page 16: SAS Slides 12 : Macros

1604/08/23SAS Techies 2009

Page 17: SAS Slides 12 : Macros

1704/08/23SAS Techies 2009

Page 18: SAS Slides 12 : Macros

%let name=sharad; data hrd.&name; data hrd.sharad;

Suppose I want thisData hrd.sharadnew

data hrd.&namenew;data hrd.&name.new

Data sharad.sasdData &name.sasd -

sharadsasdWhere sharad is a libnameData &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&& - &

1804/08/23SAS Techies 2009

Page 19: SAS Slides 12 : Macros

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

19

%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;

04/08/23SAS Techies 2009

Page 20: SAS Slides 12 : Macros

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.  

20

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

04/08/23SAS Techies 2009

Page 21: SAS Slides 12 : Macros

%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:

' "  ) (

2104/08/23SAS Techies 2009

Page 22: SAS Slides 12 : Macros

%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 %).

2204/08/23SAS Techies 2009

Page 23: SAS Slides 12 : Macros

%upcasewhere paid="%upcase(&paidval)";

%SUBSTR %substr(&date,3)

%SCAN %scan(&c,1,*);

%SYSFUNC%sysfunc(today(),weekdate.)

%INDEX

%LENGTH

%qupcase %QSUBSTR %QSCAN Function  %QSYSFUNC

2304/08/23SAS Techies 2009

Page 24: SAS Slides 12 : Macros

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.

2404/08/23SAS Techies 2009

Page 25: SAS Slides 12 : Macros

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……

25

data hrd.overtime; set hrd.temp(keep=name overtime); if overtime ne .; TotalOvertime+overtime; run;title "Temporary Employees Worked &total OT Hours"; 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 "Temporary Employees Worked &total OT Hours"; proc print data=hrd.overtime; run;

04/08/23SAS Techies 2009

Page 26: SAS Slides 12 : Macros

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

26

data hrd.overtime; set hrd.temp(keep=name overtime); if overtime ne .; TotalOvertime+overtime; call symput('total',put(totalovertime,2.)); run;

title "Temporary Employees Worked &total OT Hours"; proc print data=hrd.overtime; run;

04/08/23SAS Techies 2009

Page 27: SAS Slides 12 : Macros

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 automatically 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.

2704/08/23SAS Techies 2009

Page 28: SAS Slides 12 : Macros

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-:date3from sasuser.schedulewhere year(begin_date)=2002order 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'

2804/08/23SAS Techies 2009

Page 29: SAS Slides 12 : Macros

Global Symbol Table

TEACH1 Hallis, Dr. George

TEACH2 Wickam, Dr. Alice

TEACH3 Forest, Mr. Peter

CRS 3

SYMGET(‘macro-variable’)

29

%let crsid=C003;    

proc sql;create view subcrsid asselect

student_name,student_company,paid

From sasuser.allwhere

course_code=symget('crsid');     quit;        teacher=symget('teach'||left(course_number));

04/08/23SAS Techies 2009

Page 30: SAS Slides 12 : Macros

%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.

3004/08/23SAS Techies 2009

Page 31: SAS Slides 12 : Macros

When you call a macro in your SAS program, the word scanner passes the macro call to the macro processor, because the percent sign that precedes the macro name is a macro trigger.

When the macro processor receives %macro-name, it ◦ searches the designated SAS catalog (Work.Sasmacr by

default) for an entry named Macro-name.Macro. ◦ executes compiled macro language statements within Macro-name.

◦ sends any remaining text in Macro-name to the input stack for word scanning.

◦ suspends macro execution when the SAS compiler receives a global SAS statement or when it encounters a SAS step boundary.

◦ resumes execution of macro language statements after the SAS code executes.

3104/08/23SAS Techies 2009

Page 32: SAS Slides 12 : Macros

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…

3204/08/23SAS Techies 2009

Page 33: SAS Slides 12 : Macros

%macro prtlast;    proc print

data=&syslast(obs=5);   title "Listing of &syslast data

set";    run; %mend;    data sales; price_code=1;     run; options mprint;     %prtlast

3304/08/23SAS Techies 2009

Page 34: SAS Slides 12 : Macros

%macro printdsn(dsn,vars);      proc print data=&dsn;      var &vars;      title "Listing of

%upcase(&dsn) data set";         

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.

3404/08/23SAS Techies 2009

Page 35: SAS Slides 12 : Macros

%macro printdsn(dsn=sasuser.courses,vars=course_co

de                     course_title days);  proc print data=&dsn;     var &vars;   title "Listing of %upcase(&dsn)

data set";  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

3504/08/23SAS Techies 2009

Page 36: SAS Slides 12 : Macros

%macro printdsn(dsn, vars=course_title course_code days);

proc print data=&dsn;  var &vars;title "Listing of

%upcase(&dsn) data set";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>)

3604/08/23SAS Techies 2009

Page 37: SAS Slides 12 : Macros

%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.

3704/08/23SAS Techies 2009

Page 38: SAS Slides 12 : Macros

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).

3804/08/23SAS Techies 2009

Page 39: SAS Slides 12 : Macros

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.

3904/08/23SAS Techies 2009

Page 40: SAS Slides 12 : Macros

%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;

4004/08/23SAS Techies 2009

Page 41: SAS Slides 12 : Macros

%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.

4104/08/23SAS Techies 2009

Page 42: SAS Slides 12 : Macros

42

Yes

No

YesNo

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.

 

04/08/23SAS Techies 2009

Page 43: SAS Slides 12 : Macros

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.

 

43

Yes

No

YesNo

04/08/23SAS Techies 2009

Page 44: SAS Slides 12 : Macros

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);

%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.

4404/08/23SAS Techies 2009

Page 45: SAS Slides 12 : Macros

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

4504/08/23SAS Techies 2009

Page 46: SAS Slides 12 : Macros

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.

4604/08/23SAS Techies 2009

Page 47: SAS Slides 12 : Macros

Code - c:\sasfiles\prtlast.sas   %macro prtlast;    %if &syslast ne _NULL_ %then %do;      proc print data=&syslast(obs=5);        title "Listing of &syslast data set";      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.

4704/08/23SAS Techies 2009

Page 48: SAS Slides 12 : Macros

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.

4804/08/23SAS Techies 2009

Page 49: SAS Slides 12 : Macros

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.

4904/08/23SAS Techies 2009

Page 50: SAS Slides 12 : Macros

5004/08/23SAS Techies 2009

Page 51: SAS Slides 12 : Macros

The %SYMDEL statement enables you to delete a macro variable from the global symbol table during a SAS session.

You can call a macro within a macro definition. That is, you can nest macros.

When a nested macro is called, multiple local symbol tables can exist.

The MPRINTNEST and MLOGICNEST options provide nesting information in the messages that are written to the SAS log for the MPRINT and MLOGIC options.

You cannot nest functions within %SYSFUNC, but you can use a %SYSFUNC for each function that you need, as shown in this

eg: title "Report Produced on %sysfunc(left(%sysfunc put(today(),worddate.)))";

5104/08/23SAS Techies 2009