Ever found yourself scratching your head over SAS macros with quotes? You’re not alone. SAS macros can be a bit tricky, especially when quotes come into play.
In this guide, we’ll break down how to use SAS macros with quotes, step-by-step. By the end, you’ll be a pro at handling those pesky quotation marks.
Why Quotes Matter in SAS Macros
Before explaining how to use quotes in SAS macros, let’s first understand their purpose. Quotes are used to define character strings.
However, when used within macros, they can cause errors or unexpected results. This is because SAS macros treat quotes differently, depending on whether they are single or double quotes.
Single Quotes vs Double Quotes
In SAS, single quotes (
' ') and double quotes (
" ") are not the same. Here’s a quick rundown:
- Single Quotes: Preserve the text within them. Macro variables are not resolved.
- Double Quotes: Allow macro variables to resolve.
%let name = John; %put 'Hello &name'; /* Output: Hello &name */ %put "Hello &name"; /* Output: Hello John */
The %Str and %NRStr Functions
When working with macro variables that contain special characters, using %STR and %NRSTR functions can be helpful.
- %Str: Masks a character string during compilation.
- %NRStr: Masks a character string during compilation and execution.
%let greeting = %str(Hello, "World"); %put &greeting; /* Output: Hello, "World" */
When should you use %Str and %NRStr?
%Str function allows you to mask special characters during the compilation phase.
If the argument passed to %STR or %NRSTR contains unmatched single or double quotation marks or parentheses, they should be escaped by preceding each of these characters with a % sign.
|Notation||Description||Example||Quoted Value Stored|
|%’||unmatched single quotation mark||
|%”||unmatched double quotation mark||
|%(||unmatched left parenthesis||
|%)||unmatched right parenthesis||
%macro print_quote_smiley(message, word_to_quote); %let complete_message = %str(&message "&word_to_quote"); %put &complete_message; %mend print_quote_smiley; %print_quote_smiley(message=%str(Hello,have a), word_to_quote=nice day)
Hello,have a "nice day"
%NRStr Function in Action
%NRStr function is similar to
%Str, but it also masks the string during the execution phase, not just the compilation phase.
%put "%NRSTR(&SYSDATE9)"; %put "&SYSDATE9";
Resolving macro variables within single quotes
To resolve a macro variable inside single quotes in SAS, you can use the %UNQUOTE function along with the
%STR function, %nrbquote or the %tslit function. Here is a simple example:
%let myvar = hello; %put %unquote(%str(%'&myvar%')); %put %unquote(%nrbquote('&myvar')); %put %unquote(%nrbquote('&myvar'));
69 %put %unquote(%str(%'&myvar%')); 'hello' 70 %put %unquote(%nrbquote('&myvar')); 'hello' 71 %put %unquote(%nrbquote('&myvar')); 'hello'