The most common form of the FILE statement uses a direct path to the file:
data _null_;
file "/mypath/myfolder/myfile.txt";
set work.cars;
put "TEST";
run;
Or a fileref previously assigned to a file:
filename thisFile "/mypath/myfolder/myfile.txt";
data _null_;
file thisFile;
put "TEST";
run;
In both of those cases, the DATA step file reference is static - so when the DATA step complies, it knows at compile time where to write the PUT values. But what if you wanted to conditionally determine where to write? For this, we have to delay locating the output file until execution time - so we use FILEVAR instead of the hard-coded file location.
Now, consider the code below. During the compile phase, the sashelp.class descriptor portion is read in so that the PDV variables can be properly set up for processing. But when the execution phase begins, the STOP statement stops the DATA step before the SET statement can execute, so no observations are written to dataset1 - the data set is empty.
data dataset1;
stop;
set sashelp.class(obs=1);
run;
Next, this DATA step executes:
DATA _NULL_;
/* If there are observations, proceed*/
if nobs>0 then fileloc="&FilePath";
/*Otherwise, quit here */
else stop;
SET dataset1 nobs=nobs;
file x filevar=fileloc;
IF _N_ = 1 THEN DO;
put 'First Age'; /* These are the column headers. */
END;
put Name ' ' Age;
RUN;
At compile time, the compiler notes that the FILE statement is using FILEVAR, and defers locating the output file until the FILE statement executes during the execution phase. This means that the output file isn't created yet. As usual, the compiler reads the descriptor portion for the input dataset, in this case dataset1, in order to set up the PDV. But because the descriptor data also contains the number of observations in the data set, and we have used the nobs= option on the SET statement, the compiler also populates the value of NOBS during the compile phase. So when the execution phase starts, we already know the number of observations in dataset1.
The very first thing our DATA step does is check the value of NOBS. If there are observations, the FILEVAR value is set. When the FILE statement subsequently executes, it will create our output file. But if there are no observations, the DATA step STOP statement ends processing immediately. Beacuse the FILE statement never executed, the output file was not created.
I hope that clarifies the code for you.
May the SAS be with you! Mark
... View more