Macros for SAS Application Developers
https://github.com/sasjs/core
mf_getuniquelibref.sas
Go to the documentation of this file.
1 /**
2  @file
3  @brief Returns an unused libref
4  @details Use as follows:
5 
6  libname mclib0 (work);
7  libname mclib1 (work);
8  libname mclib2 (work);
9 
10  %let libref=%mf_getuniquelibref();
11  %put &=libref;
12 
13  which returns:
14 
15 > mclib3
16 
17  A blank value is returned if no usable libname is determined.
18 
19  @param [in] prefix= (mclib) first part of the returned libref. As librefs can
20  be as long as 8 characters, a maximum length of 7 characters is premitted
21  for this prefix.
22  @param [in] maxtries= (1000) Deprecated parameter. Remains here to ensure a
23  non-breaking change. Will be removed in v5.
24 
25  @version 9.2
26  @author Allan Bowe
27 **/
28 
29 %macro mf_getuniquelibref(prefix=mclib,maxtries=1000);
30  %local x;
31 
32  %if ( %length(&prefix) gt 7 ) %then %do;
33  %put %str(ERR)OR: The prefix parameter cannot exceed 7 characters.;
34  0
35  %return;
36  %end;
37  %else %if (%sysfunc(NVALID(&prefix,v7))=0) %then %do;
38  %put %str(ERR)OR: Invalid prefix (&prefix);
39  0
40  %return;
41  %end;
42 
43  /* Set maxtries equal to '10 to the power of [# unused characters] - 1' */
44  %let maxtries=%eval(10**(8-%length(&prefix))-1);
45 
46  %do x = 0 %to &maxtries;
47  %if %sysfunc(libref(&prefix&x)) ne 0 %then %do;
48  &prefix&x
49  %return;
50  %end;
51  %let x = %eval(&x + 1);
52  %end;
53 
54  %put %str(ERR)OR: No usable libref in range &prefix.0-&maxtries;
55  %put %str(ERR)OR- Try reducing the prefix or deleting some libraries!;
56  0
57 %mend mf_getuniquelibref;