Search code examples
sassas-macro

A macro function to produce a macro variable from a data variable


data sample;
    input x $;
    datalines;
one
two
three
;

%macro variable_to_macvar(variable=, dataset=);
    proc sql noprint;
        select &variable into : outlist separated by ' ' 
        from &dataset;
    quit;
&outlist
%mend variable_to_macvar;

%put %variable_to_macvar(variable=x, dataset=sample);

Expected output: one two three. Instead I get an error. Why? Is this fixable?

I've successfully created other macros of a very similar form, where the function "returns" a value using the &macrovariable at the end of the macro without a semicolon. For example, here is a similar type of function that works:

%macro zcat(first=5, last=15, prefix=freq); 
    %let x=;   
    %do i = &first %to &last;
        %let x=&x &prefix.&i;
    %end;
    &x
%mend zcat;
%put %zcat();

Solution

  • DOSUBL is available (but experimental) in 9.3 (at least, 9.3TS1M2, which I have). This is how you'd do it.

    data sample;
        input x $;
        datalines;
    one
    two
    three
    ;
    
    %macro variable_to_macvar(variable=, dataset=);
       %let rc=%sysfunc(dosubl(%str(
        proc sql noprint;
            select &variable into : outlist separated by ' ' 
            from &dataset;
        quit;
        )));
    &outlist
    %mend variable_to_macvar;
    
    %put %variable_to_macvar(variable=x, dataset=sample);;
    

    If you can't use DOSUBL, or want to avoid experimental things, you can do this with PROC FCMP rather than a macro. If you like to write functions, PROC FCMP is probably for you: actually being able to write functions, rather than having to deal with the annoyances of the macro language.