Production Ready 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
32 @version 9.2
33 @author Allan Bowe
34**/
35
36%macro mf_getuniquefileref(prefix=_,maxtries=1000);
37 %local rc fname;
38 %if &prefix=0 %then %do;
39 %let rc=%sysfunc(filename(fname,,temp));
40 %if &rc %then %put %sysfunc(sysmsg());
41 &fname
42 %end;
43 %else %do;
44 %local x len;
45 %let len=%eval(8-%length(&prefix));
46 %let x=0;
47 %do x=0 %to &maxtries;
48 %let fname=&prefix%substr(%sysfunc(ranuni(0)),3,&len);
49 %if %sysfunc(fileref(&fname)) > 0 %then %do;
50 %let rc=%sysfunc(filename(fname,,temp));
51 %if &rc %then %put %sysfunc(sysmsg());
52 &fname
53 %return;
54 %end;
55 %end;
56 %put unable to find available fileref after &maxtries attempts;
57 %end;
58%mend mf_getuniquefileref;