I have tried this script and it is not working. It always want to declare the libname even if it already exits
%macro test;
*libname data clear;
data test;
keep response;
response =libref("data");
%if response ne 0 %then
%do;
%PUT "Creating the libname data";
LIBNAME data "&path1./data/";
%end;
run;
%mend test;
%test;
How to solve that issue
%IF cannot access values of a data step variable such as response.
Maybe like this:
/* UNTESTED CODE */
%let response = %sysfunc(libref(data));
%put &=response;
%if &response ne 0 %then %do;
%PUT Creating the libname data;
options dlcreatedir;
LIBNAME data "&path1/data";
%end;
Which brings up the question ... why bother testing? If DATA is a currently assigned libname, or if it NOT a currently assigned libname, the LIBNAME statement should execute without problems. No conditional branching is needed here.
Is this related to your earlier thread? If so, the problem I think you are having is that you never identified the cause of this error. And so that will continue to be a problem until you identify the cause and fix it. Marking the answer correct doesn't mean you have found the cause.
The LIBREF() function verifies that a libref has been assigned. If the libref is assigned, then it returns a 0; if not assigned then it returns a nonzero value.
From your code, it seems to me that you are wanting to check to see if a LIBREF has been assigned, and if not then assign it. You might try something like this:
%macro testlibref (libref, path) ;
%local libref path rc ;
%if %sysfunc(libref(&libref)) %then %let rc = %sysfunc(libname(&libref, &path) ;
%mend testlibraf ;
/* UNIX example */
%testlibref (MYLIB, /my/test/library) ;
/*Windows example */
%testlibref (MYLIB, c:\my\test\library) ;
Or you may prefer a data step to accomplish this, it can provide a little stronger control of quotes and things:
/* UNIX example */
data _null_ ;
if libref('/my/test/library') then call execute ("libname MYLIB '/my/test/library' ;") ;
run ;
/* Windows example */
data _null_ ;
if libref(''c:\my\test\library') then call execute ("libname MYLIB 'c:\my\test\library' ;") ;
run ;
You could use libname() funtion in data step to get job done.
data _null_;
response =libref("data");
put response=;
if response ne 0 then rc=libname('data','c:\temp');
run;
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
Check out this tutorial series to learn how to build your own steps in SAS Studio.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.