循环在proc sql select中

时间:2016-08-10 14:11:43

标签: sas

我需要将一个变量分解为多个变量(最大长度2000)。 例如,我的字符串的长度为10000000(10 mb)我使用:

proc sql;
create table str as 
    select
    substr(string,2000,1) as field1,
    substr(string,2000,2001) as field2,
    .......
from data_table

我可以在select语句中编写循环而不是写这些field1-field5000。 谢谢!

1 个答案:

答案 0 :(得分:1)

<强>第一

substr()函数需要3个参数

substr(string, position <, length>)

    string - string constatn or field
    position - starting position
    length - length of the string you want to return

<强>第二

proc sql中,您只能使用宏语言循环,因此您必须编写宏程序。

options mprint;

%macro substrLoop;
%let length = 2000;
%let endLoop = %eval(1000000/&length.);

proc sql;
   create table str as 
      select
      %do i = 1 %to &endLoop.;
         substr(string, %eval(1 + (&i.-1)*&length.),&length.) as field&i.
         %if &i ne &endLoop. %then ,;
      %end;
   from data_table;
quit;
%mend substrLoop;

%substrLoop

解释

options mprint;

可以查看由被调用的宏

生成的日志代码

%let length = 2000;

%let endLoop = %eval(1000000/&length.);

设置子字符串长度的macarovariables并计算循环何时结束。

%do i = 1 %to &endLoop.;
   substr(string, %eval(1 + (&i.-1)*&length.),&length.) as field&i.
   %if &i ne &endLoop. %then ,;
%end;

实际循环将substr(string, 1,2000) as field1 , substr(string, 2001,2000) as field2 ,等计算字段放入sql代码中。

需要

%if &i ne &endLoop. %then ,;来防止在上次生成的字段后放置逗号。