Return value from SAS macro

The code below shows how to return a value from a SAS macro.

/*
Returns 0 if a specific variable is not found in a dataset and 1 if it is found.
*/
%macro VarExist(_Dataset=, _Variable=);
  %local dsid rc ;
  %let dsid = %sysfunc(open(&_Dataset));

  %if (&dsid) %then %do;
     %if %sysfunc(varnum(&dsid,&_Variable)) %then 1;
     %else 0 ;
     %let rc = %sysfunc(close(&dsid));
  %end;
  %else 0;
%mend VarExist;

/*
Go to do something if the dataset sashelp.class contains the variable
age - and it does.
*/
%if %VarExist(_Dataset=sashelp.class, _Variable=age) %then
%do;
/* Something */
%end;

It is also possible to return a value from a macro using the code below. This only works for simple macros.

%macro add(no1=, no2=);
 %let result = %eval(&no1 + &no2);

 &Result
%mend;

%let sum = %add(no1=2, no2=2);

 

Inserting quoted string in where sentence

There are different possibilities when you need to quote a string in SAS.

Before you read any further! Instead of using ‘ ‘ around the macro-variable use “ “.

The SQL-statement below will not work.

proc sql noprint;
insert into ToLib.DestDataset
select *
from FromLib.SourceDataset
where Year = ‘&Year.’;
quit;

The SQL-statement below will work.

proc sql noprint;
insert into ToLib.DestDataset
select *
from FromLib.SourceDataset
where Year = “&Year.”;
quit;

If you have a macro variable containing a year that could be 2012, and you need to put ‘ ‘ or “ “ around it, you can use the macro-functions %bquote as shown below.

My program works like this. I retrieve a year variable into a macro-variable from a configuration dataset.

proc sql noprint;
select upcase(Value) into :Year
from Config.Config_data
where upcase(Name) = upcase(‘Year’);
quit;

I remove blanks (if any)

%let Year = %trim(&Year.);

When I tried to quote the macro-variabel Year (it’s a string not a numeric) to get Year = ‘2012’ I got and error

proc sql noprint;
insert into ToLib.DestDataset
select *
from FromLib.SourceDataset
where Year = %bquote(‘&Year.’);
quit;

I found out that I needed to trim the %bquote-statement again. When I did that it worked.

proc sql noprint;
insert into ToLib.DestDataset
select *
from FromLib.SourceDataset
where Year = %trim(%bquote(‘&Year.’));
quit;

Another way to solve this would be to use

proc sql noprint;
select upcase(Value) format=$quote40. into :Year
from Config.Config_data
where upcase(Name) = upcase(‘Year’);
quit;

This will put “” around the year like “2012”.

Adding path to SASAUTOS

From SAS9.2 it’s possible to add a path to eg SASAUTOS. It’s done using ‘insert’ or ‘append’.
Read more about append and insert.

options insert=(sasautos=&SASProgramPath.\Macros);

If you get a strange error, that insert isn’t recognized or something like that. The error might be caused because there’s spaces in the path, that your trying to insert.