Hello,
May anyone can explain why this code is wrong?
data want;
merge have
if x=0 then tbl1;
else then tbl2;
;
BY CustID;
run;
And why the solution is to put it in macro as this code below
%Macro conditional_merge;
data want;
merge have
%if x=0 %then tbl1;
%else %then tbl2;
;
BY CustID;
run;
%mend conditional_merge;
%conditional_merge
If you run your code, you get errors. Why? Because IF is not allowed in the middle of some other statement. IF is only allowed in IF-THEN-ELSE statements.
Also, your modification to the macro code that I provided is not correct and will not run properly, it should say
merge have
%if &x=0 %then tbl1;
%else tbl2;
;
note the ampersand, and that %ELSE %THEN is never correct syntax. Why did you change it?
@Ronein wrote:
And when use macro then if is allowed on middle of another macro ?
IF is not macro code
%IF is a macro statement, and has to follow certain rules that apply to it, just like every other SAS command. I am not using %IF in the "middle of another macro". I am using %IF to generate conditional SAS code, in some cases it generates the code TBL1, and in other cases it generates the code TBL2. It's a method to generate TBL1 in some situations and TBL2 in other situations, which seems to be what you want. You can put %IF in the middle of a DATA step command, provided proper data step syntax is produced by %IF.
You need to internalize this first:
The macro processor is a preprocessor which is used to create code.
Whenever a % or & is encountered in SAS code, the interpreter invokes the preprocessor to resolve these "macro triggers". If this resolves to some text, this text is then included in the code instead of the triggers. Only after that, the code will be interpreted.
So you can have macro triggers that result in whole steps, or just fragments that are inserted into a bigger whole.
The final code after macro resolution must be valid to work. IF is not valid within a MERGE.
The %IF is actually not "part pf the MERGE". It is just part of program text, and it "vanishes" as soon as the macro processor is invoked. The data step compiler never sees it.
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.
Ready to level-up your skills? Choose your own adventure.