如何在SAS中优雅地编写多个if-else条件?

时间:2016-12-16 02:50:08

标签: if-statement macros sas conditional

我在SAS宏中有以下if-else条件:

%if &restart_flg = Y %then %do;
%if %sysfunc(exist(&library.f2)) %then %do;
proc sql;
Connect to xxxxx as dbcon (user=xx pw=xx server=xx port=xxx database=xxxxx);

select * into :prcs_flag_cnt    
from connection to dbcon  (
select count(1)::smallint
from &library.f2
where flag = 1 and pflag <> 'N' 
);
quit;

%put Process count flag: &prcs_flag_cnt;

%if &prcs_flag_cnt > 0 %then %do;
%let rflag = Y;
%end;

%else %do;
%let rflag  = N;
%end;

%end;

%else %do;
%let rflag = N;
%end;

%end;

%else %do;
%let rflag = N;
%end;

我基本上检查特定执行是重新执行还是重新执行,并相应地填充rflag(Y表示重新启动,N表示重新启动)。首先我检查restart_flg是否为Y,如果是,我检查是否存在SAS数据集(flags2),如果存在,我检查是否存在“flag = 1和pflag&lt;&gt;'N的任何记录''条件然后相应地为rflag填充Y或N.如果restart_flg首先是N,则rflag设置为N。

如果在代码中写入的条件不那么优雅,我会找到多路的方式。有没有更好的方法来编写if-else条件或完成此功能?

谢谢!

1 个答案:

答案 0 :(得分:0)

确定,很容易:

%if &restart_flg = Y %then %do;
  %if %sysfunc(exist(&library.f2)) %then %do;
    proc sql;
    Connect to xxxxx as dbcon (user=xx pw=xx server=xx port=xxx database=xxxxx);
    select * into :prcs_flag_cnt from connection to dbcon  (
      select count(1)::smallint
      from &library.f2
      where flag = 1 and pflag <> 'N' 
    );
    quit;

    %put Process count flag: &prcs_flag_cnt;

    %if &prcs_flag_cnt > 0 %then %let rflag = Y;
    %else %let rflag  = N;
  %end;
  %else %let rflag = N;
%end;
%else %let rflag = N;

或者:

%let prcs_flag_cnt=0;
%if &restart_flg = Y and %sysfunc(exist(&library.f2)) %then %do;
  proc sql;
  Connect to xxxxx as dbcon (user=xx pw=xx server=xx port=xxx database=xxxxx);
  select * into :prcs_flag_cnt from connection to dbcon  (
    select count(1)::smallint
    from &library.f2
    where flag = 1 and pflag <> 'N' 
  );
  quit;
  %put Process count flag: &prcs_flag_cnt;
%end;

%if &prcs_flag_cnt > 0 %then %let rflag = Y;
%else %let rflag  = N;