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 [in] libds Two part dataset (or view) reference.
27 @param [in] var Variable name for which a format should be returned
28 @param [in] force=(0) 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 &sysmacroname: dataset &libds not opened! (rc=&dsid);
55 %put &sysmacroname: %sysfunc(sysmsg());
56 %return;
57 %end;
58
59 /* supply a default if no format available */
60 %if %length(&vformat)<2 & &force=1 %then %do;
61 %let vlen = %sysfunc(varlen(&dsid, &vnum));
62 %let vtype = %sysfunc(vartype(&dsid, &vnum.));
63 %if &vtype=C %then %let vformat=$&vlen..;
64 %else %let vformat=best.;
65 %end;
66
67
68 /* Close dataset */
69 %let rc = %sysfunc(close(&dsid));
70 /* Return variable format */
71 &vformat
72%mend mf_getVarFormat;