2

I have a basic question regarding the if/then structure and (over)writing a file.

My &name var is set to name_b, but aa.js is always overwritten and bb.js.

data _null_;
if "&name" = "name_a" then do;
   filename cd_file '\\path\aa.js';
end; 
else if "&name" = "name_b" then do;
   filename cd_file '\\path\bb.js';
end;
run;

What am I doing wrong?

2 Answers2

3

filename is a global statement, and should not be wrapped in a datastep.

You can use macro logic instead - eg:

%macro example();
  %let name=name_a;  /* as appropriate */
  %if &name = name_a %then %do;
    filename cd_file '\\path\aa.js';
  %end; 
  %else %if &name = name_b %then %do;
    filename cd_file '\\path\bb.js';
  %end;
%mend;
Allan Bowe
  • 12,306
  • 19
  • 75
  • 124
0

FILENAME statement is not executable, so they will happen while the data step is being compiled. So by the time your IF statement runs both FILENAME statements have already executed.

You can use the FILENAME() function instead.

Run this example to see that using the FILENAME() function makes the assignment conditional.

%let name=name_a;
%let path=%sysfunc(pathname(work));

data _null_;
if "&name" = "name_a" then do;
   filename cd_file "&path/aa.js";
end; 
else if "&name" = "name_b" then do;
   filename cd_file "&path/bb.js";
end;
run;

%put CD_FILE -> %scan(%sysfunc(pathname(cd_file)),-1,\/);

data _null_;
if "&name" = "name_a" then do;
   rc=filename('cd_file',"&path/aa.js");
end; 
else if "&name" = "name_b" then do;
   rc=filename('cd_file',"&path/bb.js");
end;
run;

%put CD_FILE -> %scan(%sysfunc(pathname(cd_file)),-1,\/);
Tom
  • 47,574
  • 2
  • 16
  • 29