在 SAS 中使用宏生成联合语句

Generating Union Statements using Macros in SAS

我有一个名为 mylib.common_noun 的 table 包含大约 2000 条记录,尽管这可能每两周更改一次。我正在尝试生成与 mylib.common_noun

中的记录数相同数量的联合语句

mylib.common_noun 的结构。两列:关键字和 dname

Keywords DNAME
A        sas1
B        sas2
C        sas3

例如mylib.common_noun包含3条记录,那么它应该根据变量dname生成联合语句然后运行下面的代码

proc sql;
create table mylib.test_union as (select * from mylib.sas1
union
select * from chug.sas2
union
select * from chug.sas3);quit;

我 运行 根据建议编写了以下代码,但它不起作用。

filename code temp;
data _null_;
    file code;
    set mylib.common_noun;
    if _n_>1 then
        put 'create table mylib.test_union as';
    else put 'union '@;
    put 'select * from ' dname;

run;
proc sql;
    OPTIONS SOURCE2;

    %include code;
    ;
quit;

日志错误:

  40            %include code;
    NOTE: %INCLUDE (level 1) file CODE is file 
    41        +union select * from mylib.sas_out1
               _____
               180
    ERROR 180-322: Statement is not valid or it is used out of proper order.

    42        +create table mylib.test_union as
    43        +select * from mylib.sas_out2
    44        +create table mylib.test_union as
    45        +select * from mylib.sas_out3

不确定如何让它发挥作用

听起来您需要从数据生成代码。虽然您可以使用宏逻辑生成代码,但仅使用常规 SAS 语句生成代码可能更容易。

您没有描述 chug.claimants 的结构,所以我们假设它有一个名为 DATASET 的变量,其值类似于 "chug.sas_claimants2"。如果没有,那么只需添加一些逻辑来从它确实具有的变量中创建这样一个值。

filename code temp;
data _null_;
  file code ;
  set chug.claimants ;
  if _n_=1 then put 'create table chug.test as' ;
  else put 'union ' @ ;
  put 'select * from ' dataset ;
run;
proc sql ;
%include code ;
  ;
quit;

不确定 PROC SQL 代码是否是生成的最佳代码。为什么不只生成一个 SET 语句?

filename code temp;
data _null_;
  file code ;
  set chug.claimants ;
  if _n_=1 then put 'set ';
  put dataset ;
run;
data chug.test ;
%include code ;
  ;
run;

您也可以使用 call execute() 来生成代码,但是这样就无法在生成和执行阶段之间停下来查看生成的代码。或者利用 PUT 语句的报告编写功能。