Pages

SyntaxHighlighter

Friday, July 15, 2016

ValidLibref Macro

Let's say you have a fairly long SAS program and near the top you assign a libref but keyed in the folder incorrectly.

It becomes frustrating to wait for the program to finish only to find out you have a bad library reference or libref. As a result, I wrote the short validlibref() macro that tests for a valid libref ( expecting a zero value ). If the libref is not valid then an ERROR message is written to the SAS log and the %abort cancel statement will stop the program from continuing but will not shut down SAS in interactive mode.

%macro validlibref( libref ) ;
  %if %sysfunc( libref( &libref. ) ) ne 0 %then %do ;
    %put %str(E)RROR: Invalid libref: &libref., terminating program. ;
    %abort cancel ;
  %end ;
%mend ;

%validlibref( sashlp )  /* used the invalid libref of SASHLP vs SASHELP */

/* these statements will not execute if there is not a valid libref */
data x ;
  x = 1 ;
run ;

46   %macro validlibref( libref ) ;
47     %if %sysfunc( libref( &libref. ) ) ne 0 %then %do ;
48       %put %str(E)RROR: Invalid libref: &libref., terminating program. ;
49       %abort cancel ;
50     %end ;
51   %mend ;
52
53   %validlibref( sashlp )
ERROR: Invalid libref: sashlp, terminating program.
ERROR: Execution canceled by an %ABORT CANCEL statement.
NOTE: The SAS System stopped processing due to receiving a CANCEL request.