Hi there!
I'm stuck with the following code (simplified version):
%macro testing(data);
%IF &data. <= '31MAY2014'd %THEN %DO;
%put 1;
%IF '31MAY2014'd < &data. <= '31DEC2014'd %THEN %DO;
%put 2;
%IF '31DEC2014'd < &data. <= '30APR2016'd %THEN %DO;
%put 3;
%mend;
%testing('30JUN2015'd);
Ideally, the code should print a '3' in the log, but it prints a 1.
I have tried with datepart() and different time formats. I need to run different macros depending on the date, but I'm not able to evaluate whether a date is within a range.
Could someone help?
Thanks in advance.
You're three steps away from having working code.
First, macro language doesn't compare dates. At least not by default. It compares character strings.
Second, a series of comparisons doesn't work the same way in macro language as it does in a DATA step.
Third, you need an %END statement for each %DO. (Those probably got dropped when simplifying the example.)
All of that can be fixed. Here's the sort of statements that would work:
%if %sysevalf(&data. <= '31MAY2014'd) %then %put 1;
%else %if %sysevalf('31MAY2014'd < &data) and %sysevalf(&data <= '31DEC2014'd) %then %put 2;
You're three steps away from having working code.
First, macro language doesn't compare dates. At least not by default. It compares character strings.
Second, a series of comparisons doesn't work the same way in macro language as it does in a DATA step.
Third, you need an %END statement for each %DO. (Those probably got dropped when simplifying the example.)
All of that can be fixed. Here's the sort of statements that would work:
%if %sysevalf(&data. <= '31MAY2014'd) %then %put 1;
%else %if %sysevalf('31MAY2014'd < &data) and %sysevalf(&data <= '31DEC2014'd) %then %put 2;
It worked! Thank you very much!
By default SAS uses the %EVAL() macro function in %IF, %WHILE and %UNTIL clauses. That function can only handle integer comparisons. It does not handle date literals (or floating point arithmetic).
Use %SYSEVALF() to evaluate values that use date literals.
Also macro code will not convert A<B<C into (A<B) and (B<C) like SAS code will. Instead if will evaluate A<B to either 0 or 1 and then test if that is <C.
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.