SlideShare a Scribd company logo
SAS/MACROS
Chapter 2. Using Macro Variable Venkata Maguluri
Section 2.1 Basic Concepts Basic Concepts
Objectives ,[object Object],[object Object],[object Object],[object Object],Basic Concepts
Global Macro Variables Whenever the SAS System is invoked, a  global  symbol table is created and initialized with  automatic   or system-defined macro variables. You can also create  user-defined   global macro variables with the %LET statement: %let city=Dallas; %let date=05JAN2000; %let amount=975; Automatic Variables Global Symbol Table .  . .  . SYSTIME  09:47 SYSVER  8.01 .  . .  . CITY  Dallas DATE  05JAN2000 AMOUNT  975 User-defined Variables Basic Concepts
Referencing a Macro Variable To substitute the value of a macro variable in your program, you must reference it. A macro variable reference ,[object Object],[object Object],Basic Concepts
Referencing a Macro Variable Global Symbol Table CITY  Dallas DATE  05JAN2000 AMOUNT  975 Example: Use a macro variable reference to make a substitution in a SAS program statement. where fee>&amount; generates WHERE FEE>975; Basic Concepts
Referencing a Macro Variable The word scanner continues to tokenize literals enclosed in  double  quotes, permitting macro variables to resolve. where cityst CONTAINS "&city";  generates   WHERE CITYST CONTAINS "Dallas"; If you need to reference a macro variable within a  literal, enclose the literal in double quotes. The word scanner does not tokenize literals enclosed in  single  quotes, so macro variables do not resolve. where cityst contains '&city';  generates   WHERE CITYST CONTAINS '&city'; Basic Concepts Global Symbol Table CITY  Dallas DATE  05JAN2000 AMOUNT  975
Referencing a Macro Variable Global Symbol Table CITY  Dallas DATE  05JAN2000 AMOUNT  975 Referencing a nonexistent macro variable results in a warning message. title "Students from &cityst";   generates WARNING: Apparent symbolic reference CITYST not resolved. When the macro processor cannot act upon a macro variable reference, a message is printed in the SAS log. Basic Concepts
Referencing a Macro Variable Global Symbol Table CITY  Dallas DATE  05JAN2000 AMOUNT  975 Referencing an invalid macro variable name results in an error message. title "Students from &the_city_in_which_the_student_is_located"; generates ERROR: Symbolic variable name THE_CITY_IN_WHICH_THE_STUDENT_IS_LOCATED must be 32 or fewer characters long. Basic Concepts
Displaying Macro Variable Values Use the SYMBOLGEN system option to monitor the value that is substituted for a macro variable referenced.  General form of the  SYMBOLGEN  system option: OPTIONS  SYMBOLGEN; This system option displays the results of resolving macro variable references in the SAS log. Note: The default option setting is  NOSYMBOLGEN . Basic Concepts
Displaying Macro Variable Values Global Symbol Table CITY  Dallas DATE  05JAN2000 AMOUNT  975 Partial SAS Log where fee>&amount; SYMBOLGEN: Macro variable AMOUNT resolves to 975 where city_state contains "&city"; SYMBOLGEN: Macro variable CITY resolves to Dallas where city_state contains ’&city’; Why is no message displayed for the final example? Basic Concepts
Displaying Macro Variable Values To verify the values of macro variables, you may want to write your own messages to the SAS log. The %PUT statement writes text to the SAS log. General form of the %PUT statement: %PUT  text ; Basic Concepts
[object Object],[object Object],[object Object],[object Object],The %PUT statement continued... Displaying Macro Variable Values Basic Concepts
[object Object],[object Object],[object Object],[object Object],Displaying Macro Variable Values Basic Concepts
Example: Write a message to the SAS log to verify the value of the macro variable CITY. Global Symbol Table CITY  Dallas DATE  05JAN2000 AMOUNT  975 Partial SAS Log %put The value of the macro variable CITY is: &city; The value of the macro variable CITY is: Dallas Displaying Macro Variable Values Basic Concepts
Section 2.2 ,[object Object]
Objectives ,[object Object],[object Object],Automatic Micro Variables
System-Defined Automatic Macro Variables ,[object Object],[object Object],[object Object],[object Object],These variables Automatic Micro Variables
Some automatic macro variables have fixed values that are set at SAS invocation: Name   Value SYSDATE  date of SAS invocation (DATE7.) SYSDATE9 date of SAS invocation (DATE9.) SYSDAY  day of the week of SAS invocation SYSTIME  time of SAS invocation SYSENV  FORE (interactive execution) BACK (noninteractive or batch execution) SYSSCP  abbreviation for the operating system used such as OpenVMS, WIN, HP 300 SYSVER  release of SAS software being used SYSJOBID identifier of current SAS session  or batch job  mainframe systems:the userid or job name other systems: the process ID (PID). System-Defined Automatic Macro Variables Automatic Micro Variables
Some automatic macro variables have values that automatically change based on submitted SAS statements: System-Defined Automatic Macro Variables Automatic Micro Variables Name  Value SYSLAST  name of most recently created SAS  data set in the form  libref.nam e.  If no data set has been created, the value is _NULL_. SYSPARM  text specified at program invocation.
Example: Substitute system information in footnotes for a report. footnote1 "Created &systime &sysday, &sysdate9"; footnote2  "on the &sysscp system using Release &sysver"; title "REVENUES FOR DALLAS TRAINING CENTER"; proc tabulate data=perm.all(keep=location course_title fee); where upcase(location)="DALLAS"; class course_title; var fee; table course_title=" " all="TOTALS", fee=" "*(n*f=3. sum*f=dollar10.) / rts=30 box="COURSE"; run; System-Defined Automatic Macro Variables Automatic Micro Variables
System-Defined Automatic Macro Variables Automatic Micro Variables
The values of automatic macro variables can be displayed in the SAS log by specifying the _AUTOMATIC_ argument in the %PUT statement. %put _automatic_; System-Defined Automatic Macro Variables Automatic Micro Variables
Partial SAS Log The values of the macro variables SYSDATE, SYSDATE9, and SYSTIME are  character strings ,  not  SAS date or time values. System-Defined Automatic Macro Variables Automatic Micro Variables
Applications for Automatic  Variables SYSDATE  Check the current date to execute programs or   on certain days of the month. Substitute  SYSDATE9 the value in a TITLE statement. SYSDAY  Check the value to run a given job on a  certain day of the week. SYSENV  Check the execution mode before submitting code that requires interactive(foreground) processing. Possible applications for automatic macro variables: Automatic Micro Variables
Applications for Automatic  Variables SYSVER Check for the release of SAS software being used before executing a job with newer features. SYSJOBID Check who is currently executing the job to restrict certain processing or issue commands specific to a user . SYSERR Check the return code from a SAS procedure or DATA step and abort the job if the return code is nonzero. SYSRC Check the return code of any system command before continuing with the job. Automatic Micro Variables
The SYSPARM Macro Variable (Self-Study) OS/390   // EXEC SAS,OPTIONS='SYSPARM=SEATTLE' BATCH   //SYSIN DD DSN= program-name,DISP=SHR TSO   sas input(''' program-name''')   opt('sysparm=SEATTLE') CMS   sas program-name (sysparm=SEATTLE) OpenVMS sas/sysparm=SEATTLE program-name Windows sas program-name -sysparm SEATTLE UNIX Using the SYSPARM= system option to supply a value for the SYSPARM macro variable at SAS invocation.  To assign the value  SEATTLE  to the SYSPARM macro variable, specify the SYSPARM= system option: Automatic Micro Variables
title "REVENUES FOR &sysparm TRAINING CENTER"; proc tabulate data=perm.all(keep=location course_title fee); where upcase(location)="&sysparm"; class course_title; var fee; table course_title=’ ’ all=’TOTALS’, fee=’ ’*(n*f=3. sum*f=dollar10.) / rts=30 box=’COURSE’; run; Example: Use one program to create a revenue report for any training center. Supply the name of the center at SAS invocation. The SYSPARM Macro Variable (Self-Study) Automatic Micro Variables
Output for SYSPARM Value of  SEATTLE The SYSPARM Macro Variable (Self-Study) Automatic Micro Variables
Section 2.3 ,[object Object]
Objectives ,[object Object],[object Object],User-Defined Micro Variables
The %LET  Statement The %LET statement enables you to define a macro variable and assign it a value. General form of the %LET statement: %LET  variable = value ; User-Defined Micro Variables
Rules for the %LET statement: ,[object Object],[object Object],[object Object],continued... The %LET  Statement User-Defined Micro Variables
Rules for the %LET statement: ,[object Object],- maximum length is 32K characters - minimum length is 0 characters  (null valu e) - numeric tokens are stored as character strings - mathematical expressions are  not  evaluated - the case of  value   is preserved - quotes bounding literals are stored as part of  value - leading and trailing blanks  are removed  from  value   before the assignment is made. The %LET  Statement User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; Value ... The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; Value Ed Norton The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ “ Joan’s Report” ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ “ Joan’s Report” ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ “ Joan’s Report” 0 ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ “ Joan’s Report” 0 3+4 ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ “ Joan’s Report” 0+3+4 3+4 ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ “ Joan’s Report” 0+3+4 3+4 varlist ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’  Ed Norton ’ “ Joan’s Report” 0+3+4 3+4 varlist name age height ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title="Joan’s Report"; %let start=; %let total=0; %let sum=3+4; %let total=&total+∑ %let x=varlist; %let &x=name age height; The %LET  Statement Examples User-Defined Micro Variables
Example: Assign the value  DALLAS  to the macro  variable SITE. Use the macro variable to control program output. %let site=DALLAS; title "REVENUES FOR &site TRAINING CENTER"; proc tabulate data=perm.all(keep=location  course_title fee); where upcase(location)="&site"; class course_title; var fee; table course_title=’ ’ all=’TOTALS’, fee=’ ’*(n*f=3. sum*f=dollar10.) / rts=30 box=’COURSE’; run; The %LET  Statement Examples User-Defined Micro Variables
PROC TABULATE Output The %LET  Statement Examples User-Defined Micro Variables
Displaying User-defined Macro Variables The values of user-defined macro variables can be displayed in the SAS log by specifying the _USER_ argument in the %PUT statement. %let city=Dallas; %let date=22MAY95; %let amount=795; %put _user_; continued... User-Defined Micro Variables
Note: The statement  %put _all_;  displays both  automatic and user-defined macro variables. Partial SAS Log Displaying User-defined Macro Variables User-Defined Micro Variables
Tips on Writing Macro-based Programs ,[object Object],[object Object],[object Object],[object Object],[object Object],If you use a macro to generate SAS code, User-Defined Micro Variables
Using Macro Functions
Objectives ,[object Object],Using Micro Functions
Many macro applications require character string manipulation. Selected macro character functions: %UPCASE translates letters from lowercase to uppercase. %SUBSTR produces a substring of a character string.  %SCAN extracts a word from a character string. %LENGTH determines the length of a character string. Using Micro Functions
Macro functions have the same basic syntax as the corresponding DATA step functions and yield similar results. Manipulating Character Strings Using Micro Functions
Most comparison operators in the SAS language are case sensitive. Example: Create a summary of total fees  outstanding for each course. %let paidval=n; proc means data=perm.all sum maxdec=0; where paid="&paidval"; var fee; class course_title; title "Outstanding Fees for Each Course"; run; Using Micro Functions
Because the  value  of the macro variable PAIDVAL was specified in  lowercase , the WHERE expression finds no matching observations. All the  values  of the data set variable PAID are in  uppercase . Partial Log Case of Text Issues Using Micro Functions
You can use the %UPCASE function to translate the  value  of a macro variable to uppercase  before  substituting its value in a SAS program.  General form of the %UPCASE function: % UPCASE ( argumen t) Case of Text Issues Using Micro Functions
Example: For each course, create a summary of total fees outstanding and account for case.  %let paidval=n; proc means data=perm.all sum maxdec=0; where upcase(paid)=”%upcase(&paidval)"; var fee; class course_title; title "Outstanding Fees for Each Course"; run; Case of Text Issues Using Micro Functions
Case of Text Issues Using Micro Functions
Extracting Parts of Strings ,[object Object],[object Object],The %SUBSTR function General form of the %SUBSTR function: %SUBSTR ( argumen t,  position  < ,n >) continued… Using Micro Functions
[object Object],[object Object],Extracting Parts of Strings Using Micro Functions
[object Object],[object Object],[object Object],[object Object],You can specify  argumen t,  positio n, and  n  values using General form of the %SUBSTR function: %SUBSTR ( argumen t,  position  < ,n >) It is not necessary to place  argument  in quotes because it is  always  handled as a character string by the %SUBSTR function. Extracting Parts of Strings Using Micro Functions
Example: Print all courses held since the start of the current month. Use the %SUBSTR  function and SYSDATE9 macro variable to determine the month and year. proc print data=perm.schedule; where begin_date between &quot;01%substr(&sysdate9,3)&quot;d and &quot;&sysdate9&quot;d; title &quot;All Courses Held So Far This Month&quot;; title2 &quot;(as of &sysdate9)&quot;; run; Extracting Parts of Strings Using Micro Functions
Extracting Parts of Strings Using Micro Functions
You can assign several words to a macro variable’s value and extract them with the %SCAN function. General form of the %SCAN function: %SCAN ( argument ,  n  <  , delimiter s>) Extracting Parts of Strings Using Micro Functions
[object Object],[object Object],[object Object],[object Object],The %SCAN function Extracting Parts of Strings Using Micro Functions
[object Object],[object Object],[object Object],[object Object],%SCAN ( argument ,  n  <  , delimiter s>) You can specify values for  argument ,   n , and  delimiters  using The value of  n  can also be an arithmetic expression that yields an  integer . Extracting Parts of Strings Using Micro Functions
Example: Use PROC DATASETS to investigate the structure of the last data set created. data work.thisyear; set perm.schedule; where year(begin_date) = year(“sysdate9”d); run; %let libref=%scan(&syslast,1); %let dsname=%scan(&syslast,2,.); proc datasets lib=&libref nolist; title &quot;Contents of the Data Set &syslast&quot;; contents data=&dsname; run; quit; Extracting Parts of Strings Using Micro Functions
Partial Output Extracting Parts of Strings Using Micro Functions
By using the automatic macro variables  SYSDATE9  and  SYSTIME  you can include the date and time in a title: title &quot;Report Produced on &sysdate9.&quot;; title2 &quot;at &systime.&quot;; generates Using Micro Functions
SYSDATE9  represents the  date  that the  SAS session started  and  SYSTIME  represents the  time  the  SAS session started .  If you started your interactive SAS session at 10:30 PM yesterday, what  date and time  would be in your report? What if you wanted to see the date or time in some other format besides DATE9.? Other SAS Functions Using Micro Functions
You can utilize the %SYSFUNC macro function  to execute SAS functions.  Example: The following code was submitted on Friday,  June 9, 2000: title &quot;%sysfunc(today(),weekdate.) - SALES REPORT&quot;; The title on the next report would be Friday, June 9, 2000 – SALES REPORT Other SAS Functions Using Micro Functions
General form of the %SYSFUNC function: %SYSFUNC (function(argument(s)) <,format>) ,[object Object],[object Object],[object Object],Other SAS Functions Using Micro Functions
All SAS functions can be used with %SYSFUNC except: DIF DIM HBOUND IORCMSG INPUT LAG LBOUND MISSING PUT RESOLVE SYMGET  All Variable Information Functions Other SAS Functions Using Micro Functions
Combining Macro Variable References with Text
Objectives ,[object Object],Combining Micro Variable references with Text
You can reference macro variables anywhere in your program. Some applications may require placing a macro variable reference adjacent to leading and/or trailing text tex t &variable &variable text tex t &variable text or referencing adjacent macro variables &variable &variable in order to build a new token. Combining Macro Variable references with Text
You can place text immediately before a macro variable reference to build a new token. Example: Data sets are stored in a SAS data library with this naming convention: Y yymon yy  can be  90 ,  91 ,  92 ,  93 ,  94 , and so on. mon  can be  JAN ,  FEB ,  MAR , and so on. Write a program that uses a macro variable to build the month portion of the SAS data set name. Combining Macro Variable references with Text
%let month=jan; proc chart data=perm.y90 &month ; hbar week / sumvar=sale; run; proc plot data=perm.y90 &month ; plot sale*day; run; PROC CHART DATA=PERM.Y90 JAN ; HBAR WEEK / SUMVAR=SALE; RUN; PROC PLOT DATA=PERM.Y90 JAN ; PLOT SALE*DAY; RUN; generates Combining Macro Variables with Text Combining Micro Variable references with Text
You can reference macro variables that have no blanks between them to build new tokens. Example: Modify the previous program to allow both the month  and the year  to be  substituted. %let year=90 ; %let month=jan; proc chart data=perm.y &year &month; hbar week / sumvar=sale; run; proc plot data=perm.y &year &month; plot sale*day; run; Combining Macro Variables with Text Combining Micro Variable references with Text
PROC CHART DATA=PERM.Y 90 JAN; HBAR WEEK / SUMVAR=SALE; RUN; PROC PLOT DATA=PERM.Y 90 JAN; PLOT SALE*DAY; RUN; The generated program is identical to the program in the previous example. Combining Macro Variables with Text Combining Micro Variable references with Text
You can place text immediately after a macro variable reference if it does not change the macro variable name. Example: Modify the previous program to  substitute the name of an analysis  variable. %let year=90; %let month=jan; %let var=sale; proc chart data=perm.y&year&month; hbar week / sumvar =&var ; run; proc plot data=perm.y&year&month; plot  &var *day; run; Combining Macro Variables with Text Combining Micro Variable references with Text
PROC CHART DATA=PERM.Y90JAN; HBAR WEEK / SUMVAR= SALE ; RUN; PROC PLOT DATA=PERM.Y90JAN; PLOT  SALE *DAY; RUN; The generated program is identical to the program in the previous example. Combining Macro Variables with Text Combining Micro Variable references with Text
Example: Modify the previous program to allow a base SAS or SAS/GRAPH procedure. /* GRAPHICS should be null or G */ %let graphics=g ; %let year=90; %let month=jan; %let var=sale; proc  &graphicschart  data=perm.y&year&month; hbar week / sumvar=&var; run; proc  &graphicsplot  data=perm.y&year&month; plot &var*day; run; What is wrong with this program? Combining Macro Variables with Text Combining Micro Variable references with Text
SAS interprets the macro variable’s name to be GRAPHICSCHART because there is no delimiter between the macro reference and the rest of the text. Partial Log Combining Macro Variables with Text Combining Micro Variable references with Text
Macro Variable Name Delimiter The word scanner recognizes the end of a macro variable name when it encounters a character that cannot be part of the name token. A  period ( .) is a special character that is treated as part of the macro variable reference and does not appear when the macro variable is resolved. Combining Micro Variable references with Text
Example: Correct the resolution problem in the previous example. %let graphics=g; %let year=90; %let month=jan; %let var=sale; proc  &graphics. chart data=perm.y&year&month; hbar week / sumvar=&var; run; proc  &graphics. plot data=perm.y&year&month; plot &var*day; run; Macro Variable Name Delimiter Combining Micro Variable references with Text
[object Object],[object Object],[object Object],If these SAS statements are executed, the PROC  GCHART  DATA=PERM.Y90JAN; HBAR WEEK / SUMVAR=SALE; RUN; PROC  GPLOT  DATA=PERM.Y90JAN; PLOT SALE*DAY; RUN; The SAS compiler receives Macro Variable Name Delimiter Combining Micro Variable references with Text
Example: Modify the previous program to include a macro variable used to define the libref. %let lib=perm; %let graphics=g; %let year=90; %let month=jan; %let var=sale; libname &lib ’SAS-data-library’; proc &graphics.chart data =&lib. y&year&month; hbar week / sumvar=&var; run; proc &graphics.plot data =&lib. y&year&month; plot &var*day; run; What is the problem this time? Macro Variable Name Delimiter Combining Micro Variable references with Text
The statements %let lib=perm; ... libname  &lib  'SAS-data-library'; proc &graphics.chart data= &lib .y &year&month ; ... proc &graphics.plot data =&lib .y &year&month ; LIBNAME  PERM  'SAS-data-library'; PROC GCHART DATA= PERM Y 90JAN ; HBAR WEEK / SUMVAR=SALE; RUN; PROC GPLOT DATA= PERM Y 90JAN ; PLOT SALE*DAY; RUN; send these statements to the SAS compiler: The period after  &lib  is interpreted as a delimiter. Macro Variable Name Delimiter Combining Micro Variable references with Text
Use another period after the delimiter period to supply the needed token. %let lib=perm; ... libname  &lib  'SAS-data-library'; proc &graphics.chart data= &lib ..y &year&month ; ... proc &graphics.plot data =&lib ..y &year&month ; Macro Variable Name Delimiter Combining Micro Variable references with Text
proc &graphics.chart data= &lib ..y &year&month ; ... PROC GCHART DATA= PERM .Y 90JAN ; ... The first period is treated as a macro variable name delimiter. The second period is simply text. The compiler receives delimiter text Macro Variable Name Delimiter Combining Micro Variable references with Text
Quoting in the Macro Facility
Objectives ,[object Object],[object Object],Quoting Micro Facility
The SAS language uses matched pairs of quotes to distinguish character constants from names. The quotes are not stored as part of the token they define. data one; var='TEXT';  run; VAR is stored as a four-byte variable with the value  TEXT .   If  TEXT  were not enclosed in quotes, it would be treated as  a variable name . Quoting Micro Facility
proc print; title &quot;Joan’s Report&quot;; run; The title text is  Joan’s Report  and does not contain the  outer matched quotes . The outer quotes are double quotes to prevent  ambiguity  with respect to the  unmatched single quote  (apostrophe) within the text. Quoting Micro Facility
Suppose you want to store one or more SAS statements in a macro variable. options symbolgen; %let prog=data new; x=1; run; &prog proc print; run; Quoting Micro Facility
How do you explain the processing reported in this SAS log? Quoting Micro Facility
In the previous example, SAS interpreted the first “;” as the end of the macro assignment statement. In some applications you need to  mask  the meaning of text you want to assign to a macro variable. You can use  macro quoting functions  to remove the normal syntactic meaning of tokens. Need for Macro Quoting Quoting Micro Facility
The %STR function is used to protect  (quot e) tokens so the macro processor does not interpret them as macro-level syntax. General form of the %STR function: %STR ( argumen t) argument can be any combination of text and macro triggers. Quoting Micro Facility
[object Object],[object Object],The %STR function +  -  *  /  ,  <  >  =  blank LT  EQ  GT  AND  OR  NOT  LE  GE  NE continued... The %STR Function Quoting Micro Facility
[object Object],[object Object],The %STR function also Note: The %NRSTR function performs the same  quoting function as %STR, except it also quotes macro triggers (& and %). The %STR Function Quoting Micro Facility
There are a number of ways that text can be quoted. Method One: Quote all text. %let prog=%str(data new; x=1; run;); The %STR Function Quoting Micro Facility
Method Two: Quote only the semicolons. %let prog=data new%str(;) x=1%str(;)run%str(;); The %STR Function Quoting Micro Facility
Method Three: Create a macro variable with a quoted value. %let s=%str(;); %let prog=data new&s x=1&s run&s; The %STR Function Quoting Micro Facility
Example: Use the %STR function to store one or more SAS statements as the value of the macro variable PROG. Display the value of PROG through the SYMBOLGEN system option using a %PUT statement. The %STR Function Quoting Micro Facility
The %STR Function Quoting Micro Facility
options symbolgen; %let text=Joan’s Report; proc print data=perm.courses; where days >3; title &quot;&text&quot;; run; Example: Suppose you want to assign text containing an apostrophe to a macro variable. The %STR Function Quoting Micro Facility
Partial SAS Log The %STR Function Quoting Micro Facility
The word scanner interprets the apostrophe as the beginning of a literal defined by a pair of single quotes. The %STR function can also be used to quote tokens that normally occur in pairs: ’  &quot;  )  ( The %STR Function Quoting Micro Facility
To perform this quoting, you  must precede  any of the above tokens  with a percent sign  within the %STR function argument. %let text=%str(Joan % ’s Report); %let text=Joan%str( % ’)s Report; The value of TEXT is  Joan’s Report  in both cases. The %STR Function Quoting Micro Facility
options symbolgen; %let text=%str(Joan%’s Report); proc print data=perm.courses; where days >3; title &quot;&text&quot;; run; %put The value of TEXT is: &text; Example: Use the %STR function to assign text containing an apostrophe to a macro variable. The %STR Function Quoting Micro Facility
Partial SAS Log The %STR Function Quoting Micro Facility
You were earlier introduced to the %SYSFUNC macro function and used it to include a date in a title.  For example, title &quot;Report Produced on sysfunc(today(),mmddyy10.)&quot;; results in the title Report Produced on 06/12/2000 for a report run on June 12, 2000. Quoting Micro Facility
If you wanted to use a different format, the results may  not  be what you expect. For example, title &quot;Report Produced on %sysfunc(today(),worddate.)&quot;; results in the title: Report Produced on  June 12, 2000 Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
The extra blanks are from the default length of  worddate .  You need to left-justify the resulting formatted date. Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
You cannot nest functions within %SYSFUNC, but you can use a %SYSFUNC for each function needed.  Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
However, the code title “Report Produced on %sysfunc(left(%sysfunc(today(),worddate.))))”; results in the following error message: ERROR:The function LEFT referenced by the %SYSFUN or %QSYSFUNC macro function has too many arguments. Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
The LEFT function expects only  one  argument.  However, you are passing it &quot;June 12, 2000&quot;.  It is interpreting the comma as the delimiter between  two  arguments. Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
You can mask the comma by using the  %QSYSFUNC  function instead: title &quot;Report Produced on %sysfunc(left(%qsysfunc(today(),worddate.))))&quot;; The title is now: Report Produced on June 12, 2000 Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
 

More Related Content

What's hot

Utility Procedures in SAS
Utility Procedures in SASUtility Procedures in SAS
Utility Procedures in SAS
guest2160992
 
SAS ODS HTML
SAS ODS HTMLSAS ODS HTML
SAS ODS HTML
guest2160992
 
Sas summary guide
Sas summary guideSas summary guide
Sas summary guide
Ashish K Sharma
 
MYSQL
MYSQLMYSQL
Sas Functions INDEX / INDEXC / INDEXW
Sas Functions INDEX / INDEXC / INDEXWSas Functions INDEX / INDEXC / INDEXW
Sas Functions INDEX / INDEXC / INDEXW
THARUN PORANDLA
 
Top 40 sql queries for testers
Top 40 sql queries for testersTop 40 sql queries for testers
Top 40 sql queries for testers
tlvd
 
Basic Sql Handouts
Basic Sql HandoutsBasic Sql Handouts
Basic Sql Handouts
jhe04
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
Ñirmal Tatiwal
 
Learning SAS With Example by Ron Cody :Chapter 16 to Chapter 20 Solution
Learning SAS With Example by Ron Cody :Chapter 16 to Chapter 20 SolutionLearning SAS With Example by Ron Cody :Chapter 16 to Chapter 20 Solution
Learning SAS With Example by Ron Cody :Chapter 16 to Chapter 20 Solution
Vibeesh CS
 
Unit 4 plsql
Unit 4  plsqlUnit 4  plsql
Unit 4 plsql
DrkhanchanaR
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
farwa waqar
 
PLSQL
PLSQLPLSQL
Data types in c++
Data types in c++Data types in c++
Data types in c++
Venkata.Manish Reddy
 
SAS Mainframe -Program-Tips
SAS Mainframe -Program-TipsSAS Mainframe -Program-Tips
SAS Mainframe -Program-Tips
Srinimf-Slides
 
Conditional statement in c
Conditional statement in cConditional statement in c
Conditional statement in c
Muthuganesh S
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
NITISH KUMAR
 
Ejercicios resueltos de_pl-sql
Ejercicios resueltos de_pl-sqlEjercicios resueltos de_pl-sql
Ejercicios resueltos de_pl-sql
MaraMagdalenaBlancoR
 
INTRODUCTION TO SAS
INTRODUCTION TO SASINTRODUCTION TO SAS
INTRODUCTION TO SAS
Bhuwanesh Rawat
 
Triggers
TriggersTriggers
Triggers
Pooja Dixit
 
SQL
SQLSQL

What's hot (20)

Utility Procedures in SAS
Utility Procedures in SASUtility Procedures in SAS
Utility Procedures in SAS
 
SAS ODS HTML
SAS ODS HTMLSAS ODS HTML
SAS ODS HTML
 
Sas summary guide
Sas summary guideSas summary guide
Sas summary guide
 
MYSQL
MYSQLMYSQL
MYSQL
 
Sas Functions INDEX / INDEXC / INDEXW
Sas Functions INDEX / INDEXC / INDEXWSas Functions INDEX / INDEXC / INDEXW
Sas Functions INDEX / INDEXC / INDEXW
 
Top 40 sql queries for testers
Top 40 sql queries for testersTop 40 sql queries for testers
Top 40 sql queries for testers
 
Basic Sql Handouts
Basic Sql HandoutsBasic Sql Handouts
Basic Sql Handouts
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
Learning SAS With Example by Ron Cody :Chapter 16 to Chapter 20 Solution
Learning SAS With Example by Ron Cody :Chapter 16 to Chapter 20 SolutionLearning SAS With Example by Ron Cody :Chapter 16 to Chapter 20 Solution
Learning SAS With Example by Ron Cody :Chapter 16 to Chapter 20 Solution
 
Unit 4 plsql
Unit 4  plsqlUnit 4  plsql
Unit 4 plsql
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
PLSQL
PLSQLPLSQL
PLSQL
 
Data types in c++
Data types in c++Data types in c++
Data types in c++
 
SAS Mainframe -Program-Tips
SAS Mainframe -Program-TipsSAS Mainframe -Program-Tips
SAS Mainframe -Program-Tips
 
Conditional statement in c
Conditional statement in cConditional statement in c
Conditional statement in c
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
 
Ejercicios resueltos de_pl-sql
Ejercicios resueltos de_pl-sqlEjercicios resueltos de_pl-sql
Ejercicios resueltos de_pl-sql
 
INTRODUCTION TO SAS
INTRODUCTION TO SASINTRODUCTION TO SAS
INTRODUCTION TO SAS
 
Triggers
TriggersTriggers
Triggers
 
SQL
SQLSQL
SQL
 

Viewers also liked

Base SAS Full Sample Paper
Base SAS Full Sample Paper Base SAS Full Sample Paper
Base SAS Full Sample Paper
Jimmy Rana
 
Advanced SAS- Scope and opportunities
Advanced SAS- Scope and opportunitiesAdvanced SAS- Scope and opportunities
Advanced SAS- Scope and opportunities
Scholars University-San Jose , CA USA
 
SAS basics Step by step learning
SAS basics Step by step learningSAS basics Step by step learning
SAS basics Step by step learning
Venkata Reddy Konasani
 
SAS Macro practice
SAS Macro practiceSAS Macro practice
SAS Macro practice
Ping Yin
 
Basics of SAS
Basics of SASBasics of SAS
Basics of SAS
Taddesse Kassahun
 
SAS Macros
SAS MacrosSAS Macros
SAS Macros
guest2160992
 

Viewers also liked (6)

Base SAS Full Sample Paper
Base SAS Full Sample Paper Base SAS Full Sample Paper
Base SAS Full Sample Paper
 
Advanced SAS- Scope and opportunities
Advanced SAS- Scope and opportunitiesAdvanced SAS- Scope and opportunities
Advanced SAS- Scope and opportunities
 
SAS basics Step by step learning
SAS basics Step by step learningSAS basics Step by step learning
SAS basics Step by step learning
 
SAS Macro practice
SAS Macro practiceSAS Macro practice
SAS Macro practice
 
Basics of SAS
Basics of SASBasics of SAS
Basics of SAS
 
SAS Macros
SAS MacrosSAS Macros
SAS Macros
 

Similar to SAS Macros part 2

SAS Macros part 3
SAS Macros part 3SAS Macros part 3
SAS Macros part 3
venkatam
 
SAS Macros part 1
SAS Macros part 1SAS Macros part 1
SAS Macros part 1
venkatam
 
BAS 150 Lesson 8 Lecture
BAS 150 Lesson 8 LectureBAS 150 Lesson 8 Lecture
BAS 150 Lesson 8 Lecture
Wake Tech BAS
 
Combres
CombresCombres
Combres
Buu Nguyen
 
When best to use the %let statement, the symput routine, or the into clause t...
When best to use the %let statement, the symput routine, or the into clause t...When best to use the %let statement, the symput routine, or the into clause t...
When best to use the %let statement, the symput routine, or the into clause t...
Arthur8898
 
224-2009
224-2009224-2009
224-2009
Hong Zhang
 
Prog1 chap1 and chap 2
Prog1 chap1 and chap 2Prog1 chap1 and chap 2
Prog1 chap1 and chap 2
rowensCap
 
Task Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdfTask Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdf
acsmadurai
 
handout6.pdf
handout6.pdfhandout6.pdf
handout6.pdf
ssuser700533
 
Basics Of SAS Programming Language
Basics Of SAS Programming LanguageBasics Of SAS Programming Language
Basics Of SAS Programming Language
guest2160992
 
Mysqlppt
MysqlpptMysqlppt
SAS_and_R.pdf
SAS_and_R.pdfSAS_and_R.pdf
SAS_and_R.pdf
Dedy PrasTyo
 
Mysqlppt
MysqlpptMysqlppt
Oracle sql tuning
Oracle sql tuningOracle sql tuning
Oracle sql tuning
bishnupriya Panda
 
Vpd Virtual Private Database By Saurabh
Vpd   Virtual Private Database By SaurabhVpd   Virtual Private Database By Saurabh
Vpd Virtual Private Database By Saurabh
guestd83b546
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
Ranjan Kumar
 
01 surya bpc_script_ppt
01 surya bpc_script_ppt01 surya bpc_script_ppt
01 surya bpc_script_ppt
Surya Padhi
 
Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012
hwilming
 
OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL
Suraj Bang
 
Mysql
MysqlMysql
Mysql
Rathan Raj
 

Similar to SAS Macros part 2 (20)

SAS Macros part 3
SAS Macros part 3SAS Macros part 3
SAS Macros part 3
 
SAS Macros part 1
SAS Macros part 1SAS Macros part 1
SAS Macros part 1
 
BAS 150 Lesson 8 Lecture
BAS 150 Lesson 8 LectureBAS 150 Lesson 8 Lecture
BAS 150 Lesson 8 Lecture
 
Combres
CombresCombres
Combres
 
When best to use the %let statement, the symput routine, or the into clause t...
When best to use the %let statement, the symput routine, or the into clause t...When best to use the %let statement, the symput routine, or the into clause t...
When best to use the %let statement, the symput routine, or the into clause t...
 
224-2009
224-2009224-2009
224-2009
 
Prog1 chap1 and chap 2
Prog1 chap1 and chap 2Prog1 chap1 and chap 2
Prog1 chap1 and chap 2
 
Task Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdfTask Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdf
 
handout6.pdf
handout6.pdfhandout6.pdf
handout6.pdf
 
Basics Of SAS Programming Language
Basics Of SAS Programming LanguageBasics Of SAS Programming Language
Basics Of SAS Programming Language
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
SAS_and_R.pdf
SAS_and_R.pdfSAS_and_R.pdf
SAS_and_R.pdf
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Oracle sql tuning
Oracle sql tuningOracle sql tuning
Oracle sql tuning
 
Vpd Virtual Private Database By Saurabh
Vpd   Virtual Private Database By SaurabhVpd   Virtual Private Database By Saurabh
Vpd Virtual Private Database By Saurabh
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
01 surya bpc_script_ppt
01 surya bpc_script_ppt01 surya bpc_script_ppt
01 surya bpc_script_ppt
 
Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012
 
OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL
 
Mysql
MysqlMysql
Mysql
 

Recently uploaded

How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Tatiana Kojar
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
alexjohnson7307
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Jeffrey Haguewood
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
Dinusha Kumarasiri
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 

Recently uploaded (20)

How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 

SAS Macros part 2

  • 2. Chapter 2. Using Macro Variable Venkata Maguluri
  • 3. Section 2.1 Basic Concepts Basic Concepts
  • 4.
  • 5. Global Macro Variables Whenever the SAS System is invoked, a global symbol table is created and initialized with automatic or system-defined macro variables. You can also create user-defined global macro variables with the %LET statement: %let city=Dallas; %let date=05JAN2000; %let amount=975; Automatic Variables Global Symbol Table . . . . SYSTIME 09:47 SYSVER 8.01 . . . . CITY Dallas DATE 05JAN2000 AMOUNT 975 User-defined Variables Basic Concepts
  • 6.
  • 7. Referencing a Macro Variable Global Symbol Table CITY Dallas DATE 05JAN2000 AMOUNT 975 Example: Use a macro variable reference to make a substitution in a SAS program statement. where fee>&amount; generates WHERE FEE>975; Basic Concepts
  • 8. Referencing a Macro Variable The word scanner continues to tokenize literals enclosed in double quotes, permitting macro variables to resolve. where cityst CONTAINS &quot;&city&quot;; generates WHERE CITYST CONTAINS &quot;Dallas&quot;; If you need to reference a macro variable within a literal, enclose the literal in double quotes. The word scanner does not tokenize literals enclosed in single quotes, so macro variables do not resolve. where cityst contains '&city'; generates WHERE CITYST CONTAINS '&city'; Basic Concepts Global Symbol Table CITY Dallas DATE 05JAN2000 AMOUNT 975
  • 9. Referencing a Macro Variable Global Symbol Table CITY Dallas DATE 05JAN2000 AMOUNT 975 Referencing a nonexistent macro variable results in a warning message. title &quot;Students from &cityst&quot;; generates WARNING: Apparent symbolic reference CITYST not resolved. When the macro processor cannot act upon a macro variable reference, a message is printed in the SAS log. Basic Concepts
  • 10. Referencing a Macro Variable Global Symbol Table CITY Dallas DATE 05JAN2000 AMOUNT 975 Referencing an invalid macro variable name results in an error message. title &quot;Students from &the_city_in_which_the_student_is_located&quot;; generates ERROR: Symbolic variable name THE_CITY_IN_WHICH_THE_STUDENT_IS_LOCATED must be 32 or fewer characters long. Basic Concepts
  • 11. Displaying Macro Variable Values Use the SYMBOLGEN system option to monitor the value that is substituted for a macro variable referenced. General form of the SYMBOLGEN system option: OPTIONS SYMBOLGEN; This system option displays the results of resolving macro variable references in the SAS log. Note: The default option setting is NOSYMBOLGEN . Basic Concepts
  • 12. Displaying Macro Variable Values Global Symbol Table CITY Dallas DATE 05JAN2000 AMOUNT 975 Partial SAS Log where fee>&amount; SYMBOLGEN: Macro variable AMOUNT resolves to 975 where city_state contains &quot;&city&quot;; SYMBOLGEN: Macro variable CITY resolves to Dallas where city_state contains ’&city’; Why is no message displayed for the final example? Basic Concepts
  • 13. Displaying Macro Variable Values To verify the values of macro variables, you may want to write your own messages to the SAS log. The %PUT statement writes text to the SAS log. General form of the %PUT statement: %PUT text ; Basic Concepts
  • 14.
  • 15.
  • 16. Example: Write a message to the SAS log to verify the value of the macro variable CITY. Global Symbol Table CITY Dallas DATE 05JAN2000 AMOUNT 975 Partial SAS Log %put The value of the macro variable CITY is: &city; The value of the macro variable CITY is: Dallas Displaying Macro Variable Values Basic Concepts
  • 17.
  • 18.
  • 19.
  • 20. Some automatic macro variables have fixed values that are set at SAS invocation: Name Value SYSDATE date of SAS invocation (DATE7.) SYSDATE9 date of SAS invocation (DATE9.) SYSDAY day of the week of SAS invocation SYSTIME time of SAS invocation SYSENV FORE (interactive execution) BACK (noninteractive or batch execution) SYSSCP abbreviation for the operating system used such as OpenVMS, WIN, HP 300 SYSVER release of SAS software being used SYSJOBID identifier of current SAS session or batch job mainframe systems:the userid or job name other systems: the process ID (PID). System-Defined Automatic Macro Variables Automatic Micro Variables
  • 21. Some automatic macro variables have values that automatically change based on submitted SAS statements: System-Defined Automatic Macro Variables Automatic Micro Variables Name Value SYSLAST name of most recently created SAS data set in the form libref.nam e. If no data set has been created, the value is _NULL_. SYSPARM text specified at program invocation.
  • 22. Example: Substitute system information in footnotes for a report. footnote1 &quot;Created &systime &sysday, &sysdate9&quot;; footnote2 &quot;on the &sysscp system using Release &sysver&quot;; title &quot;REVENUES FOR DALLAS TRAINING CENTER&quot;; proc tabulate data=perm.all(keep=location course_title fee); where upcase(location)=&quot;DALLAS&quot;; class course_title; var fee; table course_title=&quot; &quot; all=&quot;TOTALS&quot;, fee=&quot; &quot;*(n*f=3. sum*f=dollar10.) / rts=30 box=&quot;COURSE&quot;; run; System-Defined Automatic Macro Variables Automatic Micro Variables
  • 23. System-Defined Automatic Macro Variables Automatic Micro Variables
  • 24. The values of automatic macro variables can be displayed in the SAS log by specifying the _AUTOMATIC_ argument in the %PUT statement. %put _automatic_; System-Defined Automatic Macro Variables Automatic Micro Variables
  • 25. Partial SAS Log The values of the macro variables SYSDATE, SYSDATE9, and SYSTIME are character strings , not SAS date or time values. System-Defined Automatic Macro Variables Automatic Micro Variables
  • 26. Applications for Automatic Variables SYSDATE Check the current date to execute programs or on certain days of the month. Substitute SYSDATE9 the value in a TITLE statement. SYSDAY Check the value to run a given job on a certain day of the week. SYSENV Check the execution mode before submitting code that requires interactive(foreground) processing. Possible applications for automatic macro variables: Automatic Micro Variables
  • 27. Applications for Automatic Variables SYSVER Check for the release of SAS software being used before executing a job with newer features. SYSJOBID Check who is currently executing the job to restrict certain processing or issue commands specific to a user . SYSERR Check the return code from a SAS procedure or DATA step and abort the job if the return code is nonzero. SYSRC Check the return code of any system command before continuing with the job. Automatic Micro Variables
  • 28. The SYSPARM Macro Variable (Self-Study) OS/390 // EXEC SAS,OPTIONS='SYSPARM=SEATTLE' BATCH //SYSIN DD DSN= program-name,DISP=SHR TSO sas input(''' program-name''') opt('sysparm=SEATTLE') CMS sas program-name (sysparm=SEATTLE) OpenVMS sas/sysparm=SEATTLE program-name Windows sas program-name -sysparm SEATTLE UNIX Using the SYSPARM= system option to supply a value for the SYSPARM macro variable at SAS invocation. To assign the value SEATTLE to the SYSPARM macro variable, specify the SYSPARM= system option: Automatic Micro Variables
  • 29. title &quot;REVENUES FOR &sysparm TRAINING CENTER&quot;; proc tabulate data=perm.all(keep=location course_title fee); where upcase(location)=&quot;&sysparm&quot;; class course_title; var fee; table course_title=’ ’ all=’TOTALS’, fee=’ ’*(n*f=3. sum*f=dollar10.) / rts=30 box=’COURSE’; run; Example: Use one program to create a revenue report for any training center. Supply the name of the center at SAS invocation. The SYSPARM Macro Variable (Self-Study) Automatic Micro Variables
  • 30. Output for SYSPARM Value of SEATTLE The SYSPARM Macro Variable (Self-Study) Automatic Micro Variables
  • 31.
  • 32.
  • 33. The %LET Statement The %LET statement enables you to define a macro variable and assign it a value. General form of the %LET statement: %LET variable = value ; User-Defined Micro Variables
  • 34.
  • 35.
  • 36. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; Value ... The %LET Statement Examples User-Defined Micro Variables
  • 37. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; Value Ed Norton The %LET Statement Examples User-Defined Micro Variables
  • 38. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 39. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ “ Joan’s Report” ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 40. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ “ Joan’s Report” ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 41. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ “ Joan’s Report” 0 ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 42. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ “ Joan’s Report” 0 3+4 ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 43. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ “ Joan’s Report” 0+3+4 3+4 ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 44. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ “ Joan’s Report” 0+3+4 3+4 varlist ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 45. Use the rules on the previous page to determine the values assigned to macro variables by these %LET statements: Value Ed Norton ’ Ed Norton ’ “ Joan’s Report” 0+3+4 3+4 varlist name age height ... %let name= Ed Norton ; %let name2=’ Ed Norton ’; %let title=&quot;Joan’s Report&quot;; %let start=; %let total=0; %let sum=3+4; %let total=&total+&sum; %let x=varlist; %let &x=name age height; The %LET Statement Examples User-Defined Micro Variables
  • 46. Example: Assign the value DALLAS to the macro variable SITE. Use the macro variable to control program output. %let site=DALLAS; title &quot;REVENUES FOR &site TRAINING CENTER&quot;; proc tabulate data=perm.all(keep=location course_title fee); where upcase(location)=&quot;&site&quot;; class course_title; var fee; table course_title=’ ’ all=’TOTALS’, fee=’ ’*(n*f=3. sum*f=dollar10.) / rts=30 box=’COURSE’; run; The %LET Statement Examples User-Defined Micro Variables
  • 47. PROC TABULATE Output The %LET Statement Examples User-Defined Micro Variables
  • 48. Displaying User-defined Macro Variables The values of user-defined macro variables can be displayed in the SAS log by specifying the _USER_ argument in the %PUT statement. %let city=Dallas; %let date=22MAY95; %let amount=795; %put _user_; continued... User-Defined Micro Variables
  • 49. Note: The statement %put _all_; displays both automatic and user-defined macro variables. Partial SAS Log Displaying User-defined Macro Variables User-Defined Micro Variables
  • 50.
  • 52.
  • 53. Many macro applications require character string manipulation. Selected macro character functions: %UPCASE translates letters from lowercase to uppercase. %SUBSTR produces a substring of a character string. %SCAN extracts a word from a character string. %LENGTH determines the length of a character string. Using Micro Functions
  • 54. Macro functions have the same basic syntax as the corresponding DATA step functions and yield similar results. Manipulating Character Strings Using Micro Functions
  • 55. Most comparison operators in the SAS language are case sensitive. Example: Create a summary of total fees outstanding for each course. %let paidval=n; proc means data=perm.all sum maxdec=0; where paid=&quot;&paidval&quot;; var fee; class course_title; title &quot;Outstanding Fees for Each Course&quot;; run; Using Micro Functions
  • 56. Because the value of the macro variable PAIDVAL was specified in lowercase , the WHERE expression finds no matching observations. All the values of the data set variable PAID are in uppercase . Partial Log Case of Text Issues Using Micro Functions
  • 57. You can use the %UPCASE function to translate the value of a macro variable to uppercase before substituting its value in a SAS program. General form of the %UPCASE function: % UPCASE ( argumen t) Case of Text Issues Using Micro Functions
  • 58. Example: For each course, create a summary of total fees outstanding and account for case. %let paidval=n; proc means data=perm.all sum maxdec=0; where upcase(paid)=”%upcase(&paidval)&quot;; var fee; class course_title; title &quot;Outstanding Fees for Each Course&quot;; run; Case of Text Issues Using Micro Functions
  • 59. Case of Text Issues Using Micro Functions
  • 60.
  • 61.
  • 62.
  • 63. Example: Print all courses held since the start of the current month. Use the %SUBSTR function and SYSDATE9 macro variable to determine the month and year. proc print data=perm.schedule; where begin_date between &quot;01%substr(&sysdate9,3)&quot;d and &quot;&sysdate9&quot;d; title &quot;All Courses Held So Far This Month&quot;; title2 &quot;(as of &sysdate9)&quot;; run; Extracting Parts of Strings Using Micro Functions
  • 64. Extracting Parts of Strings Using Micro Functions
  • 65. You can assign several words to a macro variable’s value and extract them with the %SCAN function. General form of the %SCAN function: %SCAN ( argument , n < , delimiter s>) Extracting Parts of Strings Using Micro Functions
  • 66.
  • 67.
  • 68. Example: Use PROC DATASETS to investigate the structure of the last data set created. data work.thisyear; set perm.schedule; where year(begin_date) = year(“sysdate9”d); run; %let libref=%scan(&syslast,1); %let dsname=%scan(&syslast,2,.); proc datasets lib=&libref nolist; title &quot;Contents of the Data Set &syslast&quot;; contents data=&dsname; run; quit; Extracting Parts of Strings Using Micro Functions
  • 69. Partial Output Extracting Parts of Strings Using Micro Functions
  • 70. By using the automatic macro variables SYSDATE9 and SYSTIME you can include the date and time in a title: title &quot;Report Produced on &sysdate9.&quot;; title2 &quot;at &systime.&quot;; generates Using Micro Functions
  • 71. SYSDATE9 represents the date that the SAS session started and SYSTIME represents the time the SAS session started . If you started your interactive SAS session at 10:30 PM yesterday, what date and time would be in your report? What if you wanted to see the date or time in some other format besides DATE9.? Other SAS Functions Using Micro Functions
  • 72. You can utilize the %SYSFUNC macro function to execute SAS functions. Example: The following code was submitted on Friday, June 9, 2000: title &quot;%sysfunc(today(),weekdate.) - SALES REPORT&quot;; The title on the next report would be Friday, June 9, 2000 – SALES REPORT Other SAS Functions Using Micro Functions
  • 73.
  • 74. All SAS functions can be used with %SYSFUNC except: DIF DIM HBOUND IORCMSG INPUT LAG LBOUND MISSING PUT RESOLVE SYMGET All Variable Information Functions Other SAS Functions Using Micro Functions
  • 75. Combining Macro Variable References with Text
  • 76.
  • 77. You can reference macro variables anywhere in your program. Some applications may require placing a macro variable reference adjacent to leading and/or trailing text tex t &variable &variable text tex t &variable text or referencing adjacent macro variables &variable &variable in order to build a new token. Combining Macro Variable references with Text
  • 78. You can place text immediately before a macro variable reference to build a new token. Example: Data sets are stored in a SAS data library with this naming convention: Y yymon yy can be 90 , 91 , 92 , 93 , 94 , and so on. mon can be JAN , FEB , MAR , and so on. Write a program that uses a macro variable to build the month portion of the SAS data set name. Combining Macro Variable references with Text
  • 79. %let month=jan; proc chart data=perm.y90 &month ; hbar week / sumvar=sale; run; proc plot data=perm.y90 &month ; plot sale*day; run; PROC CHART DATA=PERM.Y90 JAN ; HBAR WEEK / SUMVAR=SALE; RUN; PROC PLOT DATA=PERM.Y90 JAN ; PLOT SALE*DAY; RUN; generates Combining Macro Variables with Text Combining Micro Variable references with Text
  • 80. You can reference macro variables that have no blanks between them to build new tokens. Example: Modify the previous program to allow both the month and the year to be substituted. %let year=90 ; %let month=jan; proc chart data=perm.y &year &month; hbar week / sumvar=sale; run; proc plot data=perm.y &year &month; plot sale*day; run; Combining Macro Variables with Text Combining Micro Variable references with Text
  • 81. PROC CHART DATA=PERM.Y 90 JAN; HBAR WEEK / SUMVAR=SALE; RUN; PROC PLOT DATA=PERM.Y 90 JAN; PLOT SALE*DAY; RUN; The generated program is identical to the program in the previous example. Combining Macro Variables with Text Combining Micro Variable references with Text
  • 82. You can place text immediately after a macro variable reference if it does not change the macro variable name. Example: Modify the previous program to substitute the name of an analysis variable. %let year=90; %let month=jan; %let var=sale; proc chart data=perm.y&year&month; hbar week / sumvar =&var ; run; proc plot data=perm.y&year&month; plot &var *day; run; Combining Macro Variables with Text Combining Micro Variable references with Text
  • 83. PROC CHART DATA=PERM.Y90JAN; HBAR WEEK / SUMVAR= SALE ; RUN; PROC PLOT DATA=PERM.Y90JAN; PLOT SALE *DAY; RUN; The generated program is identical to the program in the previous example. Combining Macro Variables with Text Combining Micro Variable references with Text
  • 84. Example: Modify the previous program to allow a base SAS or SAS/GRAPH procedure. /* GRAPHICS should be null or G */ %let graphics=g ; %let year=90; %let month=jan; %let var=sale; proc &graphicschart data=perm.y&year&month; hbar week / sumvar=&var; run; proc &graphicsplot data=perm.y&year&month; plot &var*day; run; What is wrong with this program? Combining Macro Variables with Text Combining Micro Variable references with Text
  • 85. SAS interprets the macro variable’s name to be GRAPHICSCHART because there is no delimiter between the macro reference and the rest of the text. Partial Log Combining Macro Variables with Text Combining Micro Variable references with Text
  • 86. Macro Variable Name Delimiter The word scanner recognizes the end of a macro variable name when it encounters a character that cannot be part of the name token. A period ( .) is a special character that is treated as part of the macro variable reference and does not appear when the macro variable is resolved. Combining Micro Variable references with Text
  • 87. Example: Correct the resolution problem in the previous example. %let graphics=g; %let year=90; %let month=jan; %let var=sale; proc &graphics. chart data=perm.y&year&month; hbar week / sumvar=&var; run; proc &graphics. plot data=perm.y&year&month; plot &var*day; run; Macro Variable Name Delimiter Combining Micro Variable references with Text
  • 88.
  • 89. Example: Modify the previous program to include a macro variable used to define the libref. %let lib=perm; %let graphics=g; %let year=90; %let month=jan; %let var=sale; libname &lib ’SAS-data-library’; proc &graphics.chart data =&lib. y&year&month; hbar week / sumvar=&var; run; proc &graphics.plot data =&lib. y&year&month; plot &var*day; run; What is the problem this time? Macro Variable Name Delimiter Combining Micro Variable references with Text
  • 90. The statements %let lib=perm; ... libname &lib 'SAS-data-library'; proc &graphics.chart data= &lib .y &year&month ; ... proc &graphics.plot data =&lib .y &year&month ; LIBNAME PERM 'SAS-data-library'; PROC GCHART DATA= PERM Y 90JAN ; HBAR WEEK / SUMVAR=SALE; RUN; PROC GPLOT DATA= PERM Y 90JAN ; PLOT SALE*DAY; RUN; send these statements to the SAS compiler: The period after &lib is interpreted as a delimiter. Macro Variable Name Delimiter Combining Micro Variable references with Text
  • 91. Use another period after the delimiter period to supply the needed token. %let lib=perm; ... libname &lib 'SAS-data-library'; proc &graphics.chart data= &lib ..y &year&month ; ... proc &graphics.plot data =&lib ..y &year&month ; Macro Variable Name Delimiter Combining Micro Variable references with Text
  • 92. proc &graphics.chart data= &lib ..y &year&month ; ... PROC GCHART DATA= PERM .Y 90JAN ; ... The first period is treated as a macro variable name delimiter. The second period is simply text. The compiler receives delimiter text Macro Variable Name Delimiter Combining Micro Variable references with Text
  • 93. Quoting in the Macro Facility
  • 94.
  • 95. The SAS language uses matched pairs of quotes to distinguish character constants from names. The quotes are not stored as part of the token they define. data one; var='TEXT'; run; VAR is stored as a four-byte variable with the value TEXT . If TEXT were not enclosed in quotes, it would be treated as a variable name . Quoting Micro Facility
  • 96. proc print; title &quot;Joan’s Report&quot;; run; The title text is Joan’s Report and does not contain the outer matched quotes . The outer quotes are double quotes to prevent ambiguity with respect to the unmatched single quote (apostrophe) within the text. Quoting Micro Facility
  • 97. Suppose you want to store one or more SAS statements in a macro variable. options symbolgen; %let prog=data new; x=1; run; &prog proc print; run; Quoting Micro Facility
  • 98. How do you explain the processing reported in this SAS log? Quoting Micro Facility
  • 99. In the previous example, SAS interpreted the first “;” as the end of the macro assignment statement. In some applications you need to mask the meaning of text you want to assign to a macro variable. You can use macro quoting functions to remove the normal syntactic meaning of tokens. Need for Macro Quoting Quoting Micro Facility
  • 100. The %STR function is used to protect (quot e) tokens so the macro processor does not interpret them as macro-level syntax. General form of the %STR function: %STR ( argumen t) argument can be any combination of text and macro triggers. Quoting Micro Facility
  • 101.
  • 102.
  • 103. There are a number of ways that text can be quoted. Method One: Quote all text. %let prog=%str(data new; x=1; run;); The %STR Function Quoting Micro Facility
  • 104. Method Two: Quote only the semicolons. %let prog=data new%str(;) x=1%str(;)run%str(;); The %STR Function Quoting Micro Facility
  • 105. Method Three: Create a macro variable with a quoted value. %let s=%str(;); %let prog=data new&s x=1&s run&s; The %STR Function Quoting Micro Facility
  • 106. Example: Use the %STR function to store one or more SAS statements as the value of the macro variable PROG. Display the value of PROG through the SYMBOLGEN system option using a %PUT statement. The %STR Function Quoting Micro Facility
  • 107. The %STR Function Quoting Micro Facility
  • 108. options symbolgen; %let text=Joan’s Report; proc print data=perm.courses; where days >3; title &quot;&text&quot;; run; Example: Suppose you want to assign text containing an apostrophe to a macro variable. The %STR Function Quoting Micro Facility
  • 109. Partial SAS Log The %STR Function Quoting Micro Facility
  • 110. The word scanner interprets the apostrophe as the beginning of a literal defined by a pair of single quotes. The %STR function can also be used to quote tokens that normally occur in pairs: ’ &quot; ) ( The %STR Function Quoting Micro Facility
  • 111. To perform this quoting, you must precede any of the above tokens with a percent sign within the %STR function argument. %let text=%str(Joan % ’s Report); %let text=Joan%str( % ’)s Report; The value of TEXT is Joan’s Report in both cases. The %STR Function Quoting Micro Facility
  • 112. options symbolgen; %let text=%str(Joan%’s Report); proc print data=perm.courses; where days >3; title &quot;&text&quot;; run; %put The value of TEXT is: &text; Example: Use the %STR function to assign text containing an apostrophe to a macro variable. The %STR Function Quoting Micro Facility
  • 113. Partial SAS Log The %STR Function Quoting Micro Facility
  • 114. You were earlier introduced to the %SYSFUNC macro function and used it to include a date in a title. For example, title &quot;Report Produced on sysfunc(today(),mmddyy10.)&quot;; results in the title Report Produced on 06/12/2000 for a report run on June 12, 2000. Quoting Micro Facility
  • 115. If you wanted to use a different format, the results may not be what you expect. For example, title &quot;Report Produced on %sysfunc(today(),worddate.)&quot;; results in the title: Report Produced on June 12, 2000 Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
  • 116. The extra blanks are from the default length of worddate . You need to left-justify the resulting formatted date. Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
  • 117. You cannot nest functions within %SYSFUNC, but you can use a %SYSFUNC for each function needed. Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
  • 118. However, the code title “Report Produced on %sysfunc(left(%sysfunc(today(),worddate.))))”; results in the following error message: ERROR:The function LEFT referenced by the %SYSFUN or %QSYSFUNC macro function has too many arguments. Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
  • 119. The LEFT function expects only one argument. However, you are passing it &quot;June 12, 2000&quot;. It is interpreting the comma as the delimiter between two arguments. Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
  • 120. You can mask the comma by using the %QSYSFUNC function instead: title &quot;Report Produced on %sysfunc(left(%qsysfunc(today(),worddate.))))&quot;; The title is now: Report Produced on June 12, 2000 Quoting with %SYSFUNC (Self-Study) Quoting Micro Facility
  • 121.