Production Ready Macros for SAS Application Developers
https://github.com/sasjs/core
mf_getvarformat.sas
Go to the documentation of this file.
1 /**
2  @file
3  @brief Returns the format of a variable
4  @details Uses varfmt function to identify the format of a particular variable.
5  Usage:
6 
7  data test;
8  format str1 $1. num1 datetime19.;
9  str2='hello mum!'; num2=666;
10  stop;
11  run;
12  %put %mf_getVarFormat(test,str1);
13  %put %mf_getVarFormat(work.test,num1);
14  %put %mf_getVarFormat(test,str2,force=1);
15  %put %mf_getVarFormat(work.test,num2,force=1);
16  %put %mf_getVarFormat(test,renegade);
17 
18  returns:
19 
20  $1.
21  DATETIME19.
22  $10.
23  8.
24  NOTE: Variable renegade does not exist in test
25 
26  @param libds Two part dataset (or view) reference.
27  @param var Variable name for which a format should be returned
28  @param force Set to 1 to supply a default if the variable has no format
29  @returns outputs format
30 
31  @author Allan Bowe
32  @version 9.2
33 **/
34 
35 %macro mf_getVarFormat(libds /* two level ds name */
36  , var /* variable name from which to return the format */
37  , force=0
38 )/*/STORE SOURCE*/;
39  %local dsid vnum vformat rc vlen vtype;
40  /* Open dataset */
41  %let dsid = %sysfunc(open(&libds));
42  %if &dsid > 0 %then %do;
43  /* Get variable number */
44  %let vnum = %sysfunc(varnum(&dsid, &var));
45  /* Get variable format */
46  %if(&vnum > 0) %then %let vformat=%sysfunc(varfmt(&dsid, &vnum));
47  %else %do;
48  %put NOTE: Variable &var does not exist in &libds;
49  %let rc = %sysfunc(close(&dsid));
50  %return;
51  %end;
52  %end;
53  %else %do;
54  %put dataset &libds not opened! (rc=&dsid);
55  %return;
56  %end;
57 
58  /* supply a default if no format available */
59  %if %length(&vformat)<2 & &force=1 %then %do;
60  %let vlen = %sysfunc(varlen(&dsid, &vnum));
61  %let vtype = %sysfunc(vartype(&dsid, &vnum.));
62  %if &vtype=C %then %let vformat=$&vlen..;
63  %else %let vformat=8.;
64  %end;
65 
66 
67  /* Close dataset */
68  %let rc = %sysfunc(close(&dsid));
69  /* Return variable format */
70  &vformat
71 %mend;