【问题标题】:SAS: macro which mimic returning value from function (empty string or macro variable)SAS:模拟函数返回值的宏(空字符串或宏变量)
【发布时间】:2018-11-06 18:44:24
【问题描述】:

我是 SAS 新手,可能天真地试图模仿在 SAS 中构建宏作为函数。

我有多个从存储过程启动的宏变量。有些可能有值,而另一些可能是空的。

%let a1 = column_name1;
%let a2 = column_name2;
%let a3 = ;

%let col1 = &a1;
%let col2 = &a2;
%let col3 = &a3;

我想在 proc sql 中使用它们:

proc sql;
  create table some_table as
  select 
  &col1 AS column1,
  &col2 AS column2,
  &col3 AS column3
  from some_table;
quit;

但是,这不适用于空变量 (&col3)。因此,我正在尝试构建某种封装它的函数。比如:

%macro macro_return_string(macro_variable);
        %if length(macro_variable) = 1 %then %do; /* if column_name# is not empty, then it len() is always >2 */
            "";
        %end;
        %else %do;
            macro_variable;
        %end;

%mend macro_return_string;

所以它会像这样使用:

%let col1 = macro_return_string(&a1); /* return column_name1 */
%let col2 = macro_return_string(&a2); /* return column_name2 */
%let col3 = macro_return_string(&a3); /* return "" */

感谢您的帮助!

有人问了here 类似的问题,但我无法解决我的问题。

【问题讨论】:

    标签: sas sas-macro


    【解决方案1】:

    您的宏的主要问题是它发出的额外分号。如果你想创建一个“函数”风格的宏,那么你不能发出一个未屏蔽的分号,因为它会终止你正在尝试构建的命令。

    %macro macro_return_string(macro_variable);
    %if 0=length(&macro_variable) %then %do; 
     " "
    %end;
    %else %do;
      &macro_variable
    %end;
    %mend macro_return_string;
    

    如果您确定要添加引号?您是否只打算使用它来创建字符变量?

    %macro macro_return_string(macro_variable,type=num);
    %if 0=length(&macro_variable) %then %do; 
     %if &type=num then . else " ";
    %end;
    %else %do;
      &macro_variable
    %end;
    %mend macro_return_string;
    

    【讨论】:

      【解决方案2】:

      宏不像其他脚本或编码语言那样是基于函数的系统。宏是一个带有副作用的文本处理系统,它可能会或可能不会发出源代码供提交系统使用。

      您的宏将在您尝试生成的 sql 语句中发出一个 "";,而分号 (;) 正在搞砸工作。如果您的%if 只有%then 而不是%then do; … %end;,则宏中的分号可能是合适的

      当宏参数中没有表达式时,将 var(1) " " 分配给列的宏应该是:

      %macro macro_return_string(macro_variable);
              %if length(&macro_variable) %then %do;/* there is something in the variable passed, resolve it for emittance as source code*/
      &macro_variable/* no semi-colon here */
              %end;
              %else %do;/* argument is empty, emit a blank character as the source code for the default expression*/
      " "/* no semi-colon here */
              %end;
      %mend macro_return_string;
      

      【讨论】:

        猜你喜欢
        • 2012-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-23
        • 1970-01-01
        相关资源
        最近更新 更多