批量更改数据集字符型变量的长度

/*作用:将数据集中字符型变量长度改成最大长度加10*/

宏的编译,宏存储

OPTIONS NOCENTER LS=MAX PS=MAX SASMSTORE=SASUSER MSTORED MAUTOSOURCE;

%MACRO M_CHANGE_LENGTH(IN_TABLE,OUT_TABLE)/STORE;
PROC CONTENTS DATA=&IN_TABLE OUT=B NOPRINT;
RUN;

/*提取字符型变量*/
DATA B(KEEP=NAME);
SET B;
IF TYPE=2;
RUN;

/*求字符型变量个数*/
DATA _NULL_;
SET B NOBS=NOBS;
CALL SYMPUTX('CHAR_NUM',NOBS);
STOP;
RUN;

/*依次求字符型变量的长度*/
%DO I=1 %TO &CHAR_NUM;
DATA _NULL_;
SET B(FIRSTOBS=&I OBS=&I);
CALL SYMPUTX('VAR_NAME',NAME);
STOP;
RUN;
%IF &I=1 %THEN %DO;
DATA TEMP(KEEP=X_&I);
SET &IN_TABLE;
X_&I=LENGTH(STRIP(&VAR_NAME.));
RUN;
%END;
%ELSE %DO;
DATA APPEND(KEEP=X_&I);
SET &IN_TABLE;
X_&I=LENGTH(STRIP(&VAR_NAME.));
RUN;
DATA TEMP;
SET TEMP;
SET APPEND;
RUN;
%END;
%END;
/*求出字符串长度的最大值*/
PROC MEANS DATA=TEMP MAX;
VAR X_1-X_&CHAR_NUM;
OUTPUT OUT=TEMP1;
RUN;
DATA TEMP1(DROP=_TYPE_ _FREQ_);
SET TEMP1;
IF _STAT_='MAX';
RUN;

PROC TRANSPOSE DATA=TEMP1 OUT=TEMP2;
VAR X_1-X_&CHAR_NUM;
RUN;

DATA TEMP2(RENAME=(COL1=OLD_LEN));
LENGTH DEF_LEN $200.;
SET B;
SET TEMP2;
NEW_LEN_0=COL1+10;
NEW_LEN=PUT(NEW_LEN_0,$32.);
DEF_LEN=CAT(NAME,' ','$',COMPRESS(NEW_LEN));
RUN;

PROC SQL NOPRINT;
SELECT DEF_LEN INTO: DEF_LEN SEPARATED BY ' ' FROM TEMP2;
QUIT;

DATA &OUT_TABLE;
LENGTH &DEF_LEN;
SET &IN_TABLE;
RUN;
%MEND;

调用宏:

OPTIONS NOCENTER LS=MAX PS=MAX SASMSTORE=SASUSER MSTORED MAUTOSOURCE;
LIBNAME S '.\DATA';
%M_CHANGE_LENGTH(S.A,S.CHANGE_A);

/*第一个参数是原数据集,第二个参数是改变长度的数据集*/

posted @ 2017-07-30 10:59  Anni爱摩天轮  阅读(332)  评论(0编辑  收藏  举报