The English language, a mishmash of words from many tongues and with rules that aren’t always consistent, sometimes causes people to stumble when writing quotes. There are numerous humorous websites with examples of incorrectly-used quotes on signs saying things like “Sandwiches Prepared ‘Fresh’,” or “Help ‘Wanted’ – Please ‘inquire’ within”.
In SAS, we sometimes use quotes incorrectly as well, and macro neophytes often ask how to know when quotes are needed around macro variables, and when they’re not. Should we quote all our macro variables (no), and if only some, which ones? To answer I say two things:
- with regard to quotes, your code should look the same whether there are macro variables inside them or not,
- if there are quoted strings inside which you insert macro variables, be sure the quotes are double.
Consider the following code, which contains a WHERE statement referencing both a character and a numeric value, and no macro triggers:
data work.test; set sashelp.class; where sex='F' and height < 63; run; proc print data=work.test; title 'Girls Below 63 Inches'; run;
Next, I add two %LET statements, and several macro variable references. Notice however that I neither add nor remove any quotes, instead the quotes stay in the same places – I simply change single quotes to double quotes:
%let sex=F; %let height=63; data work.test; set sashelp.class; where sex="&sex" and height < &height; run; proc print data=work.test; title "Girls Below &height Inches"; run;
If a macro variable is placed inside quotes, they must be double quotes because of the word scanner. The word scanner sits behind the scenes where it scans submitted code and directs it to the proper location, such as the DATA step or PROC compiler, or the macro processor. But it has another job, too. If the word scanner encounters a string in double quotes, it knows it must search inside the quotes for macro variable references. If it encounters a string in single quotes, it knows it should not search for macro variable references, instead it can sit back on its digital lawn chair and relax.
Macro variable references simply replace some code with other code. If the code being replaced is already inside quotes, you should change those quotes to double, but retain them. If the code being replaced is not quoted, neither should you quote your newly-added macro variables.