Search code examples
sassas-macro

When to quote a macro variable


In SAS, while referencing a macro variable, I see that sometimes the code uses double quotes around the macro reference, but other times, it reference the variable without the quotes.

When should I use quotes before my & and when should I not?


Solution

  • You only need to quote macro variables when you are using them in place of hard-coded non-macro-text that would normally need to be quoted - usually in proc or data step code, e.g.

    %let text = Hello;
    
    /*You need quotes here*/
    data _null_;
    put "&text";
    run;
    
    /*Otherwise you get an error, because SAS thinks hello is a variable name*/
    data _null_;
    put &text;
    run;
    
    /*If you already have quotes in your macro var, you don't need to include them again in the data step code*/
    %let text2 = "Hello";
    data _null_;
     put &text2;
    run;
    
    /*In macro statements, everything is already treated as text, so you don't need the quotes*/
    %put &text;
    
    /*If you include the quotes anyway, they are counted as part of the text for macro purposes*/
    %put "&text";
    
    
    /*When you are calling functions via %sysfunc that normally
    require a variable name or a quoted string, you don't need quotes*/
    %let emptyvar=;
    %put %sysfunc(coalescec(&emptyvar,&text));