data test;
input regionstatemonth monyy5. headcnt expenses revenue;
format month monyy5.;
cards;
EASTERN VA FEB78 10 7800 15500
SOUTHERN FL MAR78 9 9800 13500
SOUTHERN GA JAN78 5 2000 8000
NORTHERN MA MAR78 3 1500 1000
SOUTHERN FL FEB78 10 8500 11000
NORTHERN NY MAR78 5 6000 5000
EASTERN VA MAR78 11 8200 16600
PLAINS NM MAR78 2 1350 500
SOUTHERN FL JAN78 10 8000 10000
NORTHERN NY FEB78 4 3000 4000
SOUTHERN GA FEB78 7 1200 6000
;
run;
%macro test;
data ttest;
%let dsid=%sysfunc(open(test));
%if &dsid gt 0 %then %do;
%let nobs=%sysfunc(attrn(&dsid,nobs));
%do i=1 %to &nobs;
%let rc=%sysfunc(fetchobs(&dsid,&i));
%let varnume=%sysfunc(varnum(&dsid,region));
%let variable=%sysfunc(getvarc(&dsid,&varnume));
%put "&dsid";
%put "&nobs";
%put "&rc";
%put "&varnume";
%put "&variable";
%put *****************;
%end;
%let rc=%sysfunc(close(&dsid));
%end;
run;
%mend test;
%let varnume=%sysfunc(varnum(&dsid,region));/*varnum是返回变量region的位置,在这变量region是第j列,所以varnume的值为j*/
%let rc=%sysfunc(fetchobs(&dsid,&i));/*读取指定的第i条观测,若成功则返回0,返回-1表示已读取完所有观测 。
%let variable=%sysfunc(getvarc(&dsid,&varnume));/*getvarc是将第i条观测的第j(因为varnume的值为j)个变量的值赋给variable,此外getvarc是针对读取字符型的变量,getvarn是针对读取数值型的变量*/ 注:getvarc要配合fetchobs使用,fetchobs控制读取值所在的观测数。
另外
Open用来打开一个数据集并返回一个非零的描述符,参数I表示input(read only);
Attrn函数用来获取相应数据集的指定数值类型的信息(attrc用于获取指定的字符型信息),可用attrn函数计算行数列数。例如:
%let dsid=%sysfunc(open(sashelp.class,i));
%let n=%sysfunc(attrn(&dsid,nobs)); /*注:计算列数用nvars*/
%let rc=%sysfunc(close(&dsid));
%put obsnum=&n;
Close函数用于关闭数据集。