SAS:创建一个宏,为数据集中的变量添加后缀

时间:2016-12-11 06:23:09

标签: sas

我想创建一个为数据集中的变量名添加后缀的宏。下面是我的代码:

%macro add_suffix(library=,dataset=,suffix=);
    proc sql noprint;
        select cat(name, ' = ', cats('&suffix.',name )) into :rename_list separated by ' ' from
        dictionary.columns where libname = '&library.' and memname= '&dataset.';
    quit;

    proc datasets library=&library nolist nodetails;
        modify &dataset;
        rename &rename_list;
    run;

    quit;

%mend;
%add_suffix(library=OUTPUT,dataset=CA_SPREADS,suffix=CA);

它会显示错误消息:

NOTE: No rows were selected.
NOTE: PROCEDURE SQL used (Total process time):
      real time           0.00 seconds
      cpu time            0.00 seconds


WARNING: Apparent symbolic reference RENAME_LIST not resolved.
NOTE: Line generated by the invoked macro "ADD_SUFFIX".
2                                                 rename &rename_list;     run;
                                                         -
                                                         22
                                                         76
NOTE: Enter RUN; to continue or QUIT; to end the procedure.

ERROR 22-322: Expecting a name.

ERROR 76-322: Syntax error, statement will be ignored.

如果我将库和数据集名称放在引号中,它适用于第一个块,即将值添加到字符串rename_list,但不是为proc数据集步骤

3 个答案:

答案 0 :(得分:3)

%&等宏触发器在单引号内不受支持。这就是为什么你没有对你的SQL查询进行任何点击。没有库名称以&作为第一个字符。

它看起来像是有效的原因是当你在SQL语句中使用它时

catx('=',name,cats('&prefix.',name))

然后你最终得到一个像

这样的字符串
age=&prefix.age

这实际上会起作用,因为当您运行PREFIX语句时,对宏变量RENAME的引用将得到解决。

你应该使用双引号。

%macro change_names(library=,dataset=,prefix=,suffix=);
%local rename_list;
proc sql noprint;
  select catx('=',name,cats("&prefix",name,"&suffix"))
    into :rename_list separated by ' ' 
  from dictionary.columns
  where libname = %upcase("&library")
    and memname = %upcase("&dataset")
  ;
quit;

%if (&sqlobs) %then %do;
proc datasets library=&library nolist nodetails;
  modify &dataset;
    rename &rename_list;
  run;
quit;
%end;
%else %put WARNING: Did not find any variables for &library..&dataset..;
%mend change_names;

%change_names(library=OUTPUT,dataset=CA_SPREADS,prefix=CA);

答案 1 :(得分:1)

  1. 您的宏变量未被解析,因为您将它们用单引号'包裹而不是双引号"
  2. 您应该将宏的libname和memname参数设置为大写,因为这些参数在dictionary.columns中始终为大写。

答案 2 :(得分:1)

经过测试和工作。更长,但也许更初学者友好的方法。输入数据集名称以及要添加的后缀。

示例:%add_suffix(orders,_old); / *将_old后缀添加到所有变量。* /

%macro Add_Suffix(Dataset, suffix);
    proc contents noprint
        data=work.&dataset out=sjm_tmp(keep=NAME);
    run;

    data sjm_tmp2;
        set sjm_tmp;
        foobar=cats(name, '=',NAME,'&suffix.');
    run;

    proc sql noprint;
        select foobar into :sjm_list separated by ' ' from sjm_tmp2;
    quit;

    proc datasets library = work nolist;
       modify &dataset;
       rename &sjm_list;
    quit;

    proc datasets library=work noprint;  
       delete sjm_tmp sjm_tmp2 ;  
    run;
%mend Add_Suffix;