学会创建宏变量,特别是全局宏变量是应用宏的一个基础,下面我们介绍一下,创建宏变量的七种方法,并通过例子来演示。
1.通过宏函数创建宏变量。
%let dsid=%sysfunc(open(sashelp.class));
%let nvars=%sysfunc(attrn(&dsid,nvars));
%let dsid=%sysfunc(attrn(&dsid,nobs));
%let dsid=%sysfunc(close(&dsid));
%put &nvars.;
%put &nobs.;
2.通过SQL过程用变量值创建一个宏变量。
proc sql noprint;
select distinct sex
into :list_a separated by ' '
from sashelp.class;
quit;
%put &list_a.;
3.通过SQL过程创建多个宏变量
proc sql noprint;
select nvar,nobs
into :nvar, :nobs
from dictionary.tables
where libname = 'SASHELP' and memname = 'CLASS';
/*注意:此处的SASHELP和CLASS必须要大写*/
quit;
%put &nvar.;
%put &nobs.;
4.通过CONTENTS和SQL过程用变量名创建宏变量。
proc contents data=sashelp.class out=con_class;
run;
proc sql noprint;
select name,put(count(name),5.-l)
into :clist separated by ' ', :charct
from con_class
where type=2;;
quit;
%put &clist.;
%put &charct.;
5.通过SQL过程用变量名创建宏变量列表。
proc sql noprint;
selecct name
into :clist1-:clist999
from dictionary.columns
where libname = 'SASHELP' and memname = 'CLASS';
quit;
%put &clist1.;
%put &clist2.;
6.通过SQL过程用变量值创建宏变量列表
proc sql noprint;
select count(distinct sex)
into :n
from sashelp.class;
select distinct sex
into :type1 - :type%left(&n)
from sashelp.class;
quit;
%put &n.;
%put &type1.;
7.通过DATA步接口子程序CALL SYMPUTX。
data _null_;
set sashelp.class nobs=obs;
call symputx('m1',obs);
call symput('m2',obs);
Stop;
run;
%put &m1.;
%put &m2.;
data test&m1.;
x=1;
run;
data test&m2.;
x=1;
run;