41 SAS Macro Interview Questions and Answers with Examples Explanation

SAS Macro Interview Questions
SAS Macro Interview Questions and Answers with Examples and Explanation from industry experts. Here we compiled a list of real world SAS Macro Interview Questions for Experienced and Freshers, who wants to crack the SAS Interview. 

We hope that these SAS Interview Questions will help you to get the SAS Job you desire. Please go through the below listed SAS Macro Interview Questions.


SAS Macro Interview Questions

Read below list of Top 10 SAS Macro Interview Questions.

1. Can I use SAS functions within the macro facility? 
2. What quoting function should I use to mask special characters? 
3. How do I resolve a macro variable within single quotation marks? 
4. How do I resolve error messages when output that was generated with the MPRINT system option looks fine? 
5. What are the differences between the autocall facility and the stored compiled macro facility? 
6. How do I conditionally execute a macro from within a DATA step? 
7. Why does my macro variable not resolve? 
8. How can I use macros to loop through all files in a directory? 
9. Can I use DATA step variables in a %IF-%THEN statement? 
10. Why am I getting an error that states that a character operand was found in the %EVAL function?

SAS Macro Interview Questions and Answers

Read below top 10 SAS Macro Interview Questions and Answers.

Question 1: Can I use SAS functions within the macro facility? 

Answer: Yes, by using the %SYSFUNC macro function. 

Example: %SYSFUNC macro function %put %sysfunc(date(),worddate20.); 

Output: 95 %put %sysfunc(date(),worddate20.); 
October 12, 2010


Question 2: What quoting function should I use to mask special characters such as the ampersand, percent sign, parentheses, and quotation marks? 

Answer: Depends. Use compile-time or execution-time quoting functions for your situation. 


  • Compile-time quoting functions: 
  • %STR–masks commas, mnemonics, and unmatched quotation marks and parentheses. 
  • %NRSTR–masks percent signs and ampersands in addition to the other special characters. 



  • Execution-time quoting functions: 
  • %BQUOTE–masks special characters and mnemonics in resolved values during macro execution. 
  • %SUPERQ–masks special characters and mnemonics during macro execution. However, it also prevents further resolution of any macros or macro variables. 

Example: 
Unmatched Quotation Mark (‘) %let singleq=O'neill; 
 %put &singleq; 

Solution: 
%STR Function %let singleq=%str(O%'neill) %put &singleq; 3120 %put &singleq; 
O'neill 

Example: 
Percent Sign (%) %let ex=This macro is called %showme; 
 %put ex=&ex; 
20 %let ex= This macro is called %showme; 

WARNING: Apparent invocation of macro SHOWME not resolved. 
21 %put ex=&ex; 

WARNING: Apparent invocation of macro SHOWME not resolved. 

Solution: %NRSTR Function %let ex=%nrstr(This macro is called %showme); 
%put ex=&ex; 

23 %let ex=%nrstr(This macro is called %showme); 
24 %put ex=&ex; 
ex=This macro is called %showme

Example: Commas (,) 
%macro test(value); 
 %put &value; 
 %mend; 
 %let x=a,b,c; 
 %put WITH NO QUOTING FUNCTION:; 
 %test(&x);  

31 %put WITH NO QUOTING FUNCTION:; 
WITH NO QUOTING FUNCTION:
32 %test(&x); 

ERROR: More positional parameters found than defined. 

Solution: 
%BQUOTE Function %put WITH THE CORRECT QUOTING FUNCTION:; 
%test(%bquote(&x)); 

34 %put WITH THE CORRECT QUOTING FUNCTION:; 
WITH THE CORRECT QUOTING FUNCTION: 35 %test(%bquote(&x)) a,b,c 

Example: Ampersand (&) 
data _null_; call symputx(‘Milwaukee','Beer&Brats'); 
run; 
%put NOT quoted:; %put &Milwaukee;

5 %put NOT quoted:; 
NOT quoted: 
6 %put &Milwaukee; 

WARNING: Apparent symbolic reference BRATS not resolved. 
Beer&Brats 

Solution: %SUPERQ Function

 %put THIS is quoted:; 
 %put %superq(Milwaukee); 

8 %put THIS is quoted:; 
THIS is quoted: 
9 %put %superq(Milwaukee); 
Beer&Brats

SAS Macro Interview Questions Examples


Question 3: How do I resolve a macro variable within single quotation marks? 

Answer: Use the %STR and %UNQUOTE functions.

Example: %STR and %UNQUOTE functions

%let name=Fred; 
 %put %unquote(%str(%‘NAME: &name%')); 
17 %put %unquote(%str(%’NAME:&name%')); 
'NAME: Fred'


Question 4: How do I resolve error messages when output that was generated with the MPRINT system option looks fine? 

Answer: Use the %UNQUOTE function.

Example: %UNQUOTE function

options mprint; 
%macro test; 
 %let val=aaa; 
 %let test = %str(%'&val%'); 
 data _null_; 
 val = &test; 
 put val=;
 run; 
 %mend test; 
 %test  

Note: Line generated by the macro variable “TEST”. 

1 ‘aaa’ 
 - 
 386 
 --- 
 202

ERROR 386-185: Expecting an arithmetic expression. 

ERROR 202-322: The option or parameter is not recognized and will be ignored. 

Solution: %UNQUOTE Function 

 options mprint; 
 %macro test; 
 %let val = aaa; 
 %let test = %unquote(%str(%'&val%')); 
 data _null_; 
 val = &test; 
 put val=;
 run;
 %mend test;
 %test

Question 5: What are the differences between the autocall facility and the stored compiled macro facility? 

Answer: The differences are in the features for each facility. 

Autocall Facility vs. Stored Compiled Macro Facility

Features                                                 Autocall Facility             Stored Compiled Macro Facility
Easy to maintain if code is shared -                   Yes                                         Maybe
Easy to hide code to the end user                       No                                          Yes
Uses less overhead                                              No                                          Yes
Easy to transfer across platforms                        Yes                                          No


Autocall Facility in SAS Macro



  • Macro source code is implicitly included and compiled to the WORK.SASMACR catalog. 
  • To use autocall macros, you have to set the MAUTOSOURCE and the SASAUTOS= system options. 
  • The MAUTOSOURCE option activates the autocall facility. 
  • The SASAUTOS= option specifies the autocall library or libraries. 
  • To use the autocall facility, submit the following statements:  

filename fileref ‘autocall-library-path’; 
options mautosource sasautos=(sasautos fileref);

Stored Compiled Macro Facility in SAS Macro


  • The stored compiled macro facility provides access to permanent SAS catalogs from which you can invoke compiled macros directly. 
  • To use these stored compiled macros, you have to set the MSTORED and the SASMSTORE= system options. 
  • The MSTORED option searches for the compiled macros in a SAS catalog that you reference with the SASMSTORE= option. 
  • The SASMSTORE= option specifies the libref for the SAS library that contains the stored compiled macros. 
  • To use the stored compiled macro facility, submit the following statements: libname libref ‘SAS-data-library-path’; options mstored sasmstore=libref;

Question 6: How do I conditionally execute a macro from within a DATA step? 

Answer: Use the CALL EXECUTE routine.

Example: CALL EXECUTE routine

/* Compile the macro BREAK. The BYVAL */ 
 /* parameter is generated in the CALL */ 
 /* EXECUTE routine. */ 

 %macro break(byval); 
 data age_&byval;
 set sorted(where=(age=&byval));
 run;
 %mend;

 proc sort data=sashelp.class out=sorted;
 by age;
 run;

 options mprint;
 data _null_;
 set sorted;
 by age;
 if first.age then call 
 execute(‘%break(‘||age||’)’);
 run; 

Output:
MPRINT(BREAK): data age_11; 
MPRINT(BREAK): set sorted(where=(age=11)); 
MPRINT(BREAK): run; 
MPRINT(BREAK): data age_12; 
MPRINT(BREAK): set sorted(where=(age=12)); 
MPRINT(BREAK): run; 
MPRINT(BREAK): data age_13; 
MPRINT(BREAK): set sorted(where=(age=13)); 
MPRINT(BREAK): run; 
MPRINT(BREAK): data age_14; 
MPRINT(BREAK): set sorted(where=(age=14)); 
MPRINT(BREAK): run; 
MPRINT(BREAK): data age_15; 
MPRINT(BREAK): set sorted(where=(age=15)); 
MPRINT(BREAK): run; 
MPRINT(BREAK): data age_16; 
MPRINT(BREAK): set sorted(where=(age=16)); 
MPRINT(BREAK): run; 

Question 7: Why does my macro variable not resolve? 

Answer: The macro variable might not resolve for a few reasons: 

  • macro variable scope 
  • no step boundary 
  • timing issues
Reasons for Macro Variable Not Resolving:
  • Macro variable scope: Local macro variables versus global macro variables. 
  • No step boundary: The DATA step does not have an ending RUN statement before a CALL SYMPUT or a CALL SYMPUTX routine. 
  • Timing issues: a result of using the CALL EXECUTE and CALL SYMPUT routines together. 

Debugging Options: 

  1. %PUT _USER_; 
  2. %PUT _GLOBAL_; 
  3. %PUT _LOCAL_; 
  4. %PUT _ALL_; 
  5. %PUT _AUTOMATIC_;   

SAS Macro Interview Questions with Explanation


Question 8: How can I use macros to loop through all files in a directory? 

Answer: Use the %DO statement.

Example: %DO statement

%macro drive(dir,ext); 
 %let filrf=mydir; 
 %let rc=%sysfunc(filename(filrf,&dir)); 
 %let did=%sysfunc(dopen(&filrf));
 %let memcnt=%sysfunc(dnum(&did));
 %do i = 1 %to &memcnt;
 %let name=%qscan(%qsysfunc(dread(&did,&i)),-1,.);
 %if %qupcase(%qsysfunc(dread(&did,&i))) ne %qupcase(&ext) %then %do;
 %if (%superq(ext) ne and %qupcase(&name) = %qupcase(&ext)) 

or 

 (%superq(ext) = and %superq(name) ne) %then %do;
 %put %qsysfunc(dread(&did,&i));
 %end;
 %end;
 %end;
 %let rc=%sysfunc(dclose(&did));
 %mend drive;
 %drive(c:\,sas)

Question 9: Can I use DATA step variables in a %IF-%THEN statement? 

Answer: No, DATA step variables cannot be used in %IF-%THEN statements.

Question 10: How do I resolve an error stating that a character operand was found in the %EVAL function? 

Answer: Use the %SYSEVALF function.

References: MWSUG.ORG


SAS Macro Interview Questions For Beginners


1. Have you used macros? For what purpose you have used?

Yes I have, I used macros in creating analysis datasets and tables where it is necessary to make a small change through out the program and where it is necessary to use the code again and again.

2. How would you invoke a macro?

After I have defined a macro I can invoke it by adding the percent sign prefix to its name like this: % macro name a semicolon is not required when invoking a macro, though adding one generally does no harm.


3. How can you create a macro variable with in data step? 

with CALL SYMPUT

4. How would you identify a macro variable?

with Ampersand (&) sign

5. How would you define the end of a macro?

The end of the macro is defined by %Mend Statement

6. For what purposes have you used SAS macros?

If we want use a program step for executing to execute the same Proc step on multiple data sets. We can accomplish repetitive tasks quickly and efficiently. 

A macro program can be reused many times. Parameters passed to the macro program customize the results without having to change the code within the macro program. 

Macros in SAS make a small change in the program and have SAS echo that change thought that program.


7. What is the difference between %LOCAL and %GLOBAL?

% Local is a macro variable defined inside a macro.%Global is a macro variable defined in open code (outside the macro or can use anywhere).

8. How long can a macro variable be? A token?

A component of SAS known as the word scanner breaks the program text into fundamental units called tokens.
· Tokens are passed on demand to the compiler.
· The compiler then requests token until it receives a semicolon.
· Then the compiler performs the syntax check on the statement.

9. If you use a SYMPUT in a DATA step, when and where can you use the macro variable?

The macro variable created by the CALL SYMPUT routine cannot be used in the same datastep in which it got created. Other than that we can use the macro variable at any time..

10. What do you code to create a macro? 

We create a macro with %MACRO statement and end a macro with %MEND statemnt.

SAS Macro Inteview Questions for Experienced


11. What is the difference between %PUT and SYMBOLGEN?

%PUT is used to display user defined messages on log window after execution of a program where as % SYMBOLGEN is used to print the value of a macro variable resolved, in log window.

12. How do you add a number to a macro variable?

Using %eval function or %sysevalf function if the number is a floating number.

13. Can you execute a macro within a macro? Describe.

Yes, Such macros are called nested macros. They can be obtained by using symget and call symput macros.

14. If you need the value of a variable rather than the variable itself what would you use to load the value to a macro variable?

If we need a value of a macro variable then we must define it in such terms so that we can call them everywhere in the program. Define it as Global. There are different ways of assigning a global variable. Simplest method is %LET.

Ex: A, is macro variable. Use following statement to assign the value of a rather than the variable itself
%Let A=xyz; %put x="&A";

This will assign "xyz" to x, not the variable xyz to x.

15. Can you execute macro within another macro? If so, how would SAS know where the current macro ended and the new one began?

Yes, I can execute macro within a macro, we call it as nesting of macros, which is allowed.
Every macro's beginning is identified the keyword %macro and end with %mend.

16. How are parameters passed to a macro?

A macro variable defined in parentheses in a %MACRO statement is a macro parameter. Macro parameters allow you to pass information into a macro.

Here is a simple example:

%macro plot(yvar= ,xvar= );
proc plot;
plot &yvar*&xvar;
run;
%mend plot;
%plot(age,sex)


17. How would you code a macro statement to produce information on the SAS log?

This statement can be coded anywhere

OPTIONS MPRINT MLOGIC MERROR SYMBOLGEN;

18. How we can call macros with in data step?

We can call the macro with
CALL SYMPUT,
Proc SQL ,
%LET statement. and macro parameters.

19. Tell me about call symput?

CALL SYMPUT takes a value from a data step and assigns it to a macro variable. I can then use this macro variable in later steps. To assign a value to a single macro variable,

I use CALL SYMPUT with this general form:

CALL SYMPUT (“macro-variable-name”, value);

Where macro-variable-name, enclosed in quotation marks, is the name of a macro variable, and value is the value I want to assign to that macro variable. 

Value can be the name of a variable whose value SAS will use, or it can be a constant value enclosed quotation marks.


CALL SYMPUT is often used in if-then statements such as this:

If age>=18 then call symput (“status”,”adult”);
else call symput (“status”,”minor”);

These statements create a macro variable named &status and assign to it a value of either adult or minor depending on the variable age.

Caution: We cannot create a macro variable with CALL SYMPUT and use it in the same data step because SAS does not assign a value to the macro variable until the data step executes. 

Data steps executes when SAS encounters a step boundary such as a subsequent data, proc, or run statement.

SAS Interview Questions and Answers


20. Tell me about % include and % eval?

The %include statement, despite its percent sign, is not a macro statement and is always executed in SAS, though it can be conditionally executed in a macro.It can be used to setting up a macro library. But this is a least approach.

The use of %include does not actually set up a library. The %include statement points to a file and when it executed the indicated file (be it a full program, macro definition, or a statement fragment) is inserted into the calling program at the location of the call.

When using the %include building a macro library, the included file will usually contain one or more macro definitions.%EVAL is a widely used yet frequently misunderstood SAS(r) macro language function due to its seemingly simple form.

However, when its actual argument is a complex macro expression interlaced with special characters, mixed arithmetic and logical operators, or macro quotation functions, its usage and result become elusive and problematic. %IF condition in macro is evaluated by %eval, to reduce it to true or false.

21. Describe the ways in which you can create macro variables?

There are the 5 ways to create macro variables:
%Let
%Global
Call Symput
Proc SQl into clause
Macro Parameters.

22. Tell me more about the parameters in macro?

Parameters are macro variables whose value you set when you invoke a macro. To add the parameters to a macro, you simply name the macro vars names in parenthesis in the %macro statement.

Syntax:
%MACRO macro-name (parameter-1= , parameter-2= , ……parameter-n = );
macro-text%;
%MEND macro-name;
%macro_name(par1,par2,....parn);

23. What is the maximum length of the macro variable?

32 characters long.

24. Automatic variables for macro?
Every time we invoke SAS, the macro processor automatically creates certain macro var. eg: &sysdate &sysday.

25. What system options would you use to help debug a macro?
The SAS System offers users a number of useful system options to help debug macro issues and problems. The results associated with using macro options are automatically displayed on the SAS Log.

Specific options related to macro debugging appear in alphabetical order in the table below:

MEMRPT: Specifies that memory usage statistics be displayed on the SAS Log.

MERROR: SAS will issue warning if we invoke a macro that SAS didn’t find. Presents Warning Messages when there are misspellings or when an undefined macro is called.

SERROR: SAS will issue warning if we use a macro variable that SAS can’t find.

MLOGIC: SAS prints details about the execution of the macros in the log.

MPRINT: Displays SAS statements generated by macro execution are traced on the SAS Log for debugging purposes.

SYMBOLGEN: SAS prints the value of macro variables in log and also displays text from expanding macro variables to the SAS Log.

27. What are SYMGET and SYMPUT?

SYMPUT puts the value from a dataset into a macro variable where as
SYMGET gets the value from the macro variable to the dataset.

28. What are the macros you have used in your programs?

Used macros for various puposes, few of them are..

1) Macros written to determine the list of variables in a dataset:
%macro varlist (dsn);
proc contents data = &dsn out = cont noprint;
run;
%mend;
%varlist(demo);

proc sql noprint;
select distinct name into:varname1-:varname22 from cont;
quit;

%do i =1 %to &sqlobs;
%put &i &&varname&i;
%end;
%mend varlist;
%varlist(adverse)

2) Distribution or Missing / Non-Missing Values
%macro missrep (dsn, vars=_numeric_);

proc freq data=&dsn.;
tables &vars. / missing;
format _character_ $missf. _numeric_ missf.;
title1 ‘Distribution or Missing / Non-Missing Values’;
run;
%mend missrep;
%missrep(study.demog, vars=age gender bdate);

3) Written macros for sorting common variables in various datasets
%macro sortit (datasetname,pid,inverstigator);

PROC SORT DATA = &DATASETNAME;
BY &PID &INVESTIGATOR;
%mend sortit;
%sortit (ae,001,sarath);

4) Macros written to split the number of observations in a dataset

%macro split (dsnorig, dsnsplit1, dsnsplit2, obs1);
data &dsnsplit1;
set &dsnorig (obs = &obs1);
run;
data &dsnsplit2;
set &dsnorig (firstobs = %eval(&obs1 + 1));
run;
%mend split;
%split(sasuser.admit,admit4,admit5,2)

29. What is auto call macro and how to create a auto call macro? What is the use of it? How to use it in SAS with macros?

SAS Enables the user to call macros that have been stored as SAS programs.

The auto call macro facility allows users to access the same macro code from multiple SAS programs. Rather than having the same macro code for in each program where the code is required, with an autocall macro, the code is in one location. 

This permits faster updates and better consistency across all the programs.Macro set-up:The fist step is to set-up a program that contains a macro, desired to be used in multiple programs. Although the program may contain other macros and/or open code, it is advised to include only one macro.

Set MAUTOSOURSE and SASAUTOS:
Before one can use the autocall macro within a SAS program, The MAUTOSOURSE option must be set open and the SASAUTOS option should be assigned. The MAUTOSOURSE option indicates to SAS that the autocall facility is to be activated. The SASAUTOS option tells SAS where to look for the macros.

For ex: sasauto=’g:\busmeas\internal\macro\’;

30. Why and How to Use %PUT Statement:

%Put statement is similar to the PUT statement in data step, What it does is it writes text and values of macro variable after execution to the SAS System LOG. If you want to make sure your macro variable resolves as expected, you can make sure it with %PUT statement.

Unique advantage of %PUT over PUT is …you can use %PUT outside the data step whereas you can’t with PUT.

How to use %PUT:

%let program=AE;
%put program Name here as &program;

Above %put statement resolves to … %put Program Name here as AE;

What can you do with %PUT:

Numerous options are available for the %PUT statement.

%PUT _all_:
It prints all macro variables in the log that are available in all environments (global, local, user and automatic).

%PUT _automatic_:
It prints all the SAS defined automatic macro variables in the log. (ex: &sysdate, &systime ,%sysdsn, %syserr etc)

%PUT _global_:
It prints macro variables that are created by the user and available in all environments.

%PUT _local_:
It prints macro variables that are created by the user and available only in the local environment. (couldn’t be able use those macro variables outside the particular data step)

%PUT _user_:
It prints macro variables that are created by the user in each environment.


31) How to know how &&var&i or &&dsn&i resolves?

It is very confusing some times to tell rightaway how &&var&i or &&dsn&i get resolved...
but here is the simple technique you can use to know....

ex: We generally use &&var&i or &&dsn&i these macro variables when we are using a %do loop... to execute same code n number of times.

You have a dataset and it has 5 variables ... Patid sex age ethnic race wt ht;
%macro doit;
%do i=1 %to &nvars;
&&var&i
%end;
%mend doit;
So if the nvars value is 7, then the loop creates a macro variable list of
&var1 &var2 &var3 &var4 &var5 &var6 &var7
which further get resolved to
patid sex age ethnic race wt ht
You can always use Macro debugging option SYMBOLGEN to see how each macro variable got resolved.... Reference: epoch.forumotions.in


Comments

  1. Thanks for sharing this SAS interview questions with answers. It is really useful.
    SAS Training in Chennai | SAS Course in Chennai

    ReplyDelete
  2. A Computer Science portal for geeks. It contains well written, well thought and well
    explained computer science and programming articles, quizzes and practice/competitive
    programming/company interview Questions.
    website: geeksforgeeks.org

    ReplyDelete
  3. A Computer Science portal for geeks. It contains well written, well thought and well
    explained computer science and programming articles, quizzes and practice/competitive
    programming/company interview Questions.
    website: geeksforgeeks.org

    ReplyDelete
  4. A Computer Science portal for geeks. It contains well written, well thought and well
    explained computer science and programming articles, quizzes and practice/competitive
    programming/company interview Questions.
    website: geeksforgeeks.org

    ReplyDelete
  5. Hey very nice blog!!
    Hi there,I enjoy reading through your article post, I wanted to write a little comment to support you and wish you a good continuationAll the best for all your blogging efforts.
    Salesforce Training | Online Course | Certification in chennai | Salesforce Training | Online Course | Certification in bangalore | Salesforce Training | Online Course | Certification in hyderabad | Salesforce Training | Online Course | Certification in pune


    ReplyDelete
  6. I blog habitually and I truly appreciate your substance. Your article has truly topped my advantage. I'm going to bookmark your site and continue to check for new insights concerning once every week. I bought in to your RSS channel as well.
    zerodha

    ReplyDelete

Post a Comment

Popular posts from this blog