Search code examples
sasformatsas-macro

sas format variable with custom date format - how to retain formatting?


/*Create datetime format for db*/

proc format;
picture dbdate
    other = '%Y-%0m-%0d-%0H.%0M.%0S' (datatype=datetime);
run;

/*Create variable that is 24 hours ago*/

data _null_;
sdt = intnx("HOUR",datetime(),-1,"SAME");
format sdt dbdate.;
call symput ('sdt',sdt);
run;

%put &sdt;

when run the put sdt; return 2020-02-21-09.28.28 correctly, but when calling sdt later it %put &sdt; it returns the unformated value Macro variable SDT resolves to 1897896509

how do i get sdt to retain its format or do i need to keep using format sdt dbdate. somehow everytim i call the variable?

Thanks

here the later proc sql step where i need to use the sdt variable in the dbdate. format:

proc sql;
connect to db (database=bob user="&srvuser" password="&srvpass") ;
create table ted as 
select * from connection to db
(Select *
        from work 
        where num = 7387 and ADD_TMSTMP < &sdt);
disconnect from db;
quit;
run;

Solution

  • The pass through SQL requires a date value represented by the form rendered by your custom picture format. Send that rendering to the macro variable, not the underlying value.

    call symput ('sdt',put(sdt,dbdate.));
    

    You could eliminate your DATA step prior to the SQL if you coded

    proc sql;
    connect to db (database=bob user="&srvuser" password="&srvpass") ;
    create table ted as 
    select * from connection to db
    (Select *
            from work 
            where num = 7387 
            and
              ADD_TMSTMP 
              <
    
              %sysfunc(intnx(HOUR,%sysfunc(datetime()),-1,SAME),dbdate.)
    );
    disconnect from db;
    quit;
    run;
    

    If the pass through SQL needs a single quoted date representation, such as '2020-02-21-06.06.36' you will need to update your custom format to include the bounding single quotes.

    proc format;
      picture dbdate
        other = '''%Y-%0m-%0d-%0H.%0M.%0S''' (datatype=datetime);
    run;