I have about 30 datasets with a approx 20 date fields in each where the variable type varies between character and numeric as well as between date and datetime formats i.e. the following cases ...
a.) numeric - date b.) numeric - datetime c.) character - date d.) character - datetime
I want to convert each individual field to numeric and in date9. format. I tried to write the macro below which does not yield the correct results when the variable is a character string. What is going wrong? ... sas does not seem to interpret the input statement correctly if the character variable dateformat is not correctly specified.
%macro converttodate(inlib,indata,outlib,outdata,invar,outvar);
ods listing close;
ods output dataset.variables = work.formats;
proc contents data = &inlib..&indata.;
run;
data work.formats;
set work.formats;
where lowcase(compress(variable)) = lowcase(compress("&invar."));
run;
data _NULL_;
set work.formats;
call symput('dtype',compress(lowcase(type)));
call symput('dformat',compress(lowcase(format)));
call symput('dlen',compress(put(len,8.)));
run;
%PUT INVAR = ** &invar. ** OUTVAR = ** &outvar. **;
%PUT TYPE = ** &dtype. **;
%PUT FORMAT = ** &dformat. **;
%PUT LENGTH = ** &dlen. **;
%if &dtype. = num %then %do;
data &outlib..&outdata.;
length tmp_put $50;
set &inlib..&indata.;
format &outvar. date9.;
tmp_put = compress(put(&invar.,&dformat.));
if index(tmp_put,':') > 0 then &outvar. = datepart(&invar.);
else &outvar. = &invar.;
drop tmp_put;
run;
%end;
%else %do;
data &outlib..&outdata.;
set &inlib..&indata.;
format &outvar. date9.;
if index(&invar.,':') > 0 then &outvar. = datepart(input(&invar.,datetime.));
else &outvar. = input(&invar.,date.);
run;
%end;
%mend;
E.g.
data work.test;
format x1 date9. y1 datetime30.6;
x1 = mdy(10,16,1922);
x2 = put(x1,date9.);
y1 = 100000;
y2 = put(y1,datetime30.6);
run;
%converttodate(
inlib = work,
indata = test,
outlib = work,
outdata = test,
invar = x2,
outvar = x2_out);