Macros for SAS Application Developers
https://github.com/sasjs/core
mf_getuniquefileref.sas
Go to the documentation of this file.
1 /**
2  @file
3  @brief Assigns and returns an unused fileref
4  @details Using the native approach for assigning filerefs fails as some
5  procedures (such as proc http) do not recognise the temporary names (starting
6  with a hash), returning a message such as:
7 
8  > ERROR 22-322: Expecting a name.
9 
10  This macro works by attempting a random fileref (with a prefix), seeing if it
11  is already assigned, and if not - returning the fileref.
12 
13  If your process can accept filerefs with the hash (#) prefix, then set
14  `prefix=0` to revert to the native approach - which is significantly faster
15  when there are a lot of filerefs in a session.
16 
17  Use as follows:
18 
19  %let fileref1=%mf_getuniquefileref();
20  %let fileref2=%mf_getuniquefileref(prefix=0);
21  %put &fileref1 &fileref2;
22 
23  which returns filerefs similar to:
24 
25 > _7432233 #LN00070
26 
27  @param [in] prefix= (_) first part of fileref. Remember that filerefs can only
28  be 8 characters, so a 7 letter prefix would mean `maxtries` should be 10.
29  if using zero (0) as the prefix, a native assignment is used.
30  @param [in] maxtries= (1000) the last part of the libref. Must be an integer.
31  @param [in] lrecl= (32767) Provide a default lrecl with which to initialise
32  the generated fileref.
33 
34  @version 9.2
35  @author Allan Bowe
36 **/
37 
38 %macro mf_getuniquefileref(prefix=_,maxtries=1000,lrecl=32767);
39  %local rc fname;
40  %if &prefix=0 %then %do;
41  %let rc=%sysfunc(filename(fname,,temp,lrecl=&lrecl));
42  %if &rc %then %put %sysfunc(sysmsg());
43  &fname
44  %end;
45  %else %do;
46  %local x len;
47  %let len=%eval(8-%length(&prefix));
48  %let x=0;
49  %do x=0 %to &maxtries;
50  %let fname=&prefix%substr(%sysfunc(ranuni(0)),3,&len);
51  %if %sysfunc(fileref(&fname)) > 0 %then %do;
52  %let rc=%sysfunc(filename(fname,,temp,lrecl=&lrecl));
53  %if &rc %then %put %sysfunc(sysmsg());
54  &fname
55  %return;
56  %end;
57  %end;
58  %put unable to find available fileref after &maxtries attempts;
59  %end;
60 %mend mf_getuniquefileref;