【问题标题】:Execute Macro inside SQL statement在 SQL 语句中执行宏
【发布时间】:2015-07-27 11:48:31
【问题描述】:

情况:

我有一个表 mytable 有两列:tablenametablefield

|-----------|------------|
| tablename | tablefield |
|-----------|------------|
| table1    | id         |
| table2    | date       |
| table3    | etc        |
|-----------|------------|

我的核心目标基本上是,为每个这些表名创建一个Select,显示其对应表字段的MAX()值。

Proc SQL;
Select MAX(id) From table1;
Select MAX(date) From table2;
Select MAX(etc) From table3;
Quit;

ps:解决方案必须从表中拉取数据,因此无论表的值是否发生变化,解决方案都会对其进行更改。

我尝试过的:

根据我的大部分尝试,这是最复杂的,我相信最接近解决方案:

proc sql;
create table table_associations (
    memname varchar(255), dt_name varchar(255)
);

Insert Into table_associations 
values ("table1", "id")
values ("table2", "date")
values ("table3", "etc");
quit;

%Macro Max(field, table);
Select MAX(&field.) From &table.;
%mend;

proc sql;
Select table, field, (%Max(field,table))
From LIB.table_associations
quit;

创建宏,我的意图很明确,但对于这个例子,我应该解决 2 个问题:

  • SQL 语句中执行宏;并且
  • 使宏将其字符串值参数理解为SQL 命令。

【问题讨论】:

    标签: sql macros sas sas-macro


    【解决方案1】:

    在数据步骤中,您可以使用 call execute 来执行您所描述的操作。

    %Macro Max(field, table);
    proc sql;
    Select MAX(&field.) From &table.;
    quit;
    %mend;
    
    data _null_;
        set table_associations;
        call execute('%MAX('||field||','||table||')');
    run;
    

    【讨论】:

    • 你知道这个错误是什么意思吗? File LIB.TABLE_ASSOCIATIONS.DATA does not exist 我只需要解决这个问题来测试你的答案是否解决了我的问题。无论如何,谢谢!
    • 删除LIB.。我包含它是因为它在您的示例代码中,但我现在看到 table_associations 在工作目录中,应该省略 libname。
    【解决方案2】:

    这里不需要宏,因为您可以在数据步骤中使用put 语句生成代码:

    filename gencode temp;
    
    data _null_;
      set table_associations end=eof;
      file gencode;
      if _n_=1 then put 'proc sql;';
      put 'select max(' tablefield ') from ' tablename ';';
      if eof then put 'quit;';
    run;
    
    %include gencode / source2;
    filename gencode clear;
    

    代码被写入名为“gencode”的临时文件中。如果你愿意,你可以使这个文件永久化。 _n_=1end=eof 用于打印查询前后的语句。最后,%include gencode 运行代码,source2 选项将代码打印到日志中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多