Michael St Clair
Michael St Clair

Reputation: 6625

SAS Data Step if statement not working

With the below code the email always gets sent. 1 obviously does not equal 0, but yet it still runs. I have tried removing the do part but still get the same issue.

data _null_;
set TestTable;
if 1 = 0 then do;
    file sendit email
    to=("[email protected]")
    subject="Some Subject Line";
end;    
run;

Upvotes: 2

Views: 241

Answers (2)

Tom
Tom

Reputation: 51566

Use email directives to abort the message. http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a002058232.htm

data _null_;
  file sendit email to=("[email protected]") subject="Some Subject Line";
  if nobs=0 then put '!EM_ABORT!';
  set TestTable nobs=nobs;
  ....
run;

Upvotes: 1

Joe
Joe

Reputation: 63424

While the file statement is considered an executable statement (and thus should not be executed when behind a false if statement), that is not really entirely true. SAS sees the file statement during compilation, and knows that it needs to create a file to write to - and thus, it's somewhat compile-time. That's what is happening here - SAS creates the file (in this case, the email) as a result of the compiler's activity, then doesn't actually populate it with anything, but still has an email at the end of the day.

The same thing happens with any other file - like so:

data _null_;
  set sashelp.class;
  if 0 then do;
      file "c:\temp\test_non_zero.txt";
      put name $;
  end;
run;

A blank file is created by that code.

If you need to conditionally send emails, I would recommend wrapping your email code in a macro, and then calling that macro using call execute or similar from the dataset. Like so:

%macro write_email(parameters);
data _null_;
  file sendit email
  to=("[email protected]")
  subject="Some Subject Line";
run;
%mend write_email;

data _null_;
  set TestTable;
  if 0 then do;
     call execute('%write_email(parameters)');
  end;
run;

Upvotes: 7

Related Questions