Macros for SAS Application Developers
https://github.com/sasjs/core
mp_ds2fmtds.sas
Go to the documentation of this file.
1 /**
2  @file
3  @brief Converts every value in a dataset to formatted value
4  @details Converts every value to it's formatted value. All variables will
5  become character, and will be in the same order as the original dataset.
6 
7  Lengths will be adjusted according to the format lengths, where applicable.
8 
9  Usage:
10 
11  %mp_ds2fmtds(sashelp.cars,work.cars)
12  %mp_ds2fmtds(sashelp.vallopt,vw_vallopt)
13 
14  @param [in] libds The library.dataset to be converted
15  @param [out] outds The dataset to create.
16 
17  <h4> SAS Macros </h4>
18  @li mf_existds.sas
19 
20  <h4> Related Macros </h4>
21  @li mp_jsonout.sas
22 
23  @version 9.2
24  @author Allan Bowe
25 **/
26 
27 %macro mp_ds2fmtds(libds, outds
28 )/*/STORE SOURCE*/;
29 
30 /* validations */
31 
32 %if not %mf_existds(libds=&libds) %then %do;
33  %put %str(WARN)ING: &libds does not exist as either a VIEW or DATASET;
34  %return;
35 %end;
36 %if %index(&libds,.)=0 %then %let libds=WORK.&libds;
37 
38 /* grab metadata */
39 proc contents noprint data=&libds
40  out=_data_(keep=name type length format formatl formatd varnum);
41 run;
42 proc sort;
43  by varnum;
44 run;
45 
46 /* prepare formats and varnames */
47 data _null_;
48  set &syslast end=last;
49  name=upcase(name);
50  /* fix formats */
51  if type=2 or type=6 then do;
52  length fmt $49.;
53  if format='' then fmt=cats('$',length,'.');
54  else if formatl=0 then fmt=cats(format,'.');
55  else fmt=cats(format,formatl,'.');
56  newlen=max(formatl,length);
57  end;
58  else do;
59  if format='' then fmt='best.';
60  else if formatl=0 then fmt=cats(format,'.');
61  else if formatd=0 then fmt=cats(format,formatl,'.');
62  else fmt=cats(format,formatl,'.',formatd);
63  /* needs to be wide, for datetimes etc */
64  newlen=max(length,formatl,24);
65  end;
66  /* 32 char unique name */
67  newname='sasjs'!!substr(cats(put(md5(name),$hex32.)),1,27);
68 
69  call symputx(cats('name',_n_),name,'l');
70  call symputx(cats('newname',_n_),newname,'l');
71  call symputx(cats('len',_n_),newlen,'l');
72  call symputx(cats('fmt',_n_),fmt,'l');
73  call symputx(cats('type',_n_),type,'l');
74  if last then call symputx('nobs',_n_,'l');
75 run;
76 
77 /* clean up */
78 proc sql;
79 drop table &syslast;
80 
81 %if &nobs=0 %then %do;
82  %put Dataset &libds has no columns!
83  data &outds;
84  set &libds;
85  run;
86  %return;
87 %end;
88 
89 data &outds;
90  /* rename on entry */
91  set &libds(rename=(
92 %local i;
93 %do i=1 %to &nobs;
94  &&name&i=&&newname&i
95 %end;
96  ));
97 %do i=1 %to &nobs;
98  length &&name&i $&&len&i;
99  &&name&i=left(put(&&newname&i,&&fmt&i));
100  drop &&newname&i;
101 %end;
102  if _error_ then call symputx('syscc',1012);
103 run;
104 
105 %mend mp_ds2fmtds;