如果表(项目列表)是数组的变量名,则不需要宏。只需使用纯数据步骤代码并使用宏变量列出数组元素。
array orig &table;
do I = 1 to dim(orig);
put orig[I]=
end;
当宏变量包含以空格分隔的项目列表时,在宏内部使用此类通常是通过在 %do 循环内使用 %scan 解析每个项目来完成的。一个有用的例子是为 Proc SQL 语句生成一系列选择子句。
解析出每个项目的一次使用
%macro special_sauce (items=);
%local i item;
%let i = 1;
%do %while (%length(%scan(&items,&i)));
%let item = %scan(&items,&i);
%put NOTE: code generated for &=item;
/* ... emit some SAS code or code-snippet involving &item ... */
&item._squared = &item ** 2; /* emit data step source statement that presumes item is a variable name that is being squared */
%let i = %eval(&i+1);
%end;
%mend;
options mprint;
data want;
set sashelp.class;
%special_sauce(items=age height)
run;
如果需要多次使用项目列表,将各个项目存储在局部宏变量中以方便重复使用也很有帮助。
多次使用的项目列表,解析一次并将项目放入“宏数组”。实际上没有宏数组这样的东西,只是可以迭代的数字后缀符号名称的约定。
%macro special_sauce2 (items=);
%local i item itemCount;
%let i = 1;
%do %while (%length(%scan(&items,&i)));
%let item = %scan(&items,&i);
%let itemCount = &i; /* track number of items parsed */
%local item&i; /* local macro variable name with numeric suffix, sometimes called a macro array */
%let item&i = &item; /* save the extracted item */
%let i = %eval(&i+1);
%end;
/* use the items in the 'macro-array' */
%do i = 1 %to &itemCount;
%put NOTE: value of macro variable item&i is &&item&i;
&&item&i.._2 = &&item&i ** 2;
%end;
/* use the items in the 'macro-array' */
%do i = 1 %to &itemCount;
%put NOTE: Hi again, value of macro variable item&i is &&item&i;
&&item&i.._3 = &&item&i ** 3;
%end;
%mend;
options mprint;
data want;
set sashelp.class;
%special_sauce2(items=age height)
run;
良好的经验法则,如果没有必要,不要使用宏。