Thanks for writing about this topic. Using the CALL EXECUTE statement in the DATA step to generate code is extremely useful. Because this post describes several issues, I want to emphasize to your readers that the complexity in using CALL EXECUTE is because the generated SAS statements do not execute until AFTER the DATA step completes. That's why you must include “data B; set A;” and “run;” as part of the program.

You can use the OPTIONS SOURCE option to see the code that is generated by the CALL EXECUTE statements. This can be useful to understand a program that is not working correctly. For example, the following DATA step is wrong, and the SOURCE option shows why:

options source;
data wrong;
set A;
call execute(catx(' ','d =', c, ';')); /* does not work as intended */
run;

The SAS log shows that the generated statements are

d = a**2+b**2 ;
d = b/a * 2 ;
d = cos(b/a) ;
d = cdf("NORMAL", 0, a, b) ;

This is not a valid SAS program. Even if you put "DATA B; set A;" before these statements and "RUN;" after these statements, you do not get the desired answer because for every observation the final statement (d=CDF(...)) is used to assign the result to d.

This is why using the "IF _N_ =" trick is so valuable. With that trick, the correct program is implemented as follows:

options source;
data Result;
set A end=eof;
length cmd $60;
if _n_=1 then call execute('data B; set A;');
cmd = catx(' ','if _n_ eq', _n_, 'then d =', c,';');
call execute(cmd);
if eof then call execute('run;');
run;

proc print data=Result; run;
proc print data=B; run;

The log reveals that the generated statements are now correct:

data B; set A;
if _n_ eq 1 then d = a**2+b**2 ;
if _n_ eq 2 then d = b/a * 2 ;
if _n_ eq 3 then d = cos(b/a) ;
if _n_ eq 4 then d = cdf("NORMAL", 0, a, b) ;
run;

I've defined a new variable called CMD in the RESULT data set that shows the statements that will be executed when the DATA step exits. This is a useful trick.

Again, thanks for discussing this topic. For readers who might wonder when to use this technique, one application is to write a template in the Graph Template Language (GTL) that modifies a graph that is generated by a SAS procedure.