2014-11-24 37 views
1

我被卡住,试图迭代宏%do循环中的值列表。每个值都应该用作变量后缀。在迭代列表时创建后缀

该方法是基于SAS文档:http://support.sas.com/kb/26/155.html

的(简化的)代码是:

%macro loop(values);       
    %let count=%sysfunc(countw(&values)); 
    %do i = 1 %to &count;   
     %let value=%qscan(values,i,%str(,)); 
     proc sql; 
      select count(distinct hut_id) as prefix_&value. 
      from saslib.tl1_results_eval 
      group by plan_cell; 
     quit; 
    %end;                    
%mend;     
%loop(%str(a,b,c,d)) 

所得错误信息是:

MLOGIC(LOOP): %DO loop beginning; index variable I; start value is 1; stop value is 4; by value 
     is 1. 
MLOGIC(LOOP): %LET (variable name is VALUE) 
MPRINT(LOOP): proc sql; 
22: LINE and COLUMN cannot be determined. 
NOTE 242-205: NOSPOOL is on. Rerunning with OPTION SPOOL might allow recovery of the LINE and 
       COLUMN where the error has occurred. 
ERROR 22-322: Syntax error, expecting one of the following: ',', AS. 
MPRINT(LOOP): select count(distinct hut_id) as prefix_a from group by plan_cell; 
MPRINT(LOOP): quit; 

有趣的是,如果删除“count(distinct hut_id)”中的“prefix_”作为前缀_ &值。“ - 它工作得很好。不幸的是,我确实需要那里的前缀。另外,正如您在日志消息中看到的那样,PROC SQL语句最终得到了正确编译,但代码在执行之前出错。

任何想法发生了什么?谢谢!

回答

1

由于qscan功能,您正在插入不可见的引号字符。尝试:

%macro loop(values);     
    proc sql;  
    %let count=%sysfunc(countw(&values)); 
    %do i = 1 %to &count;   
     %let value=%qscan(values,i,%str(,)); 
     select count(distinct hut_id) as prefix_%unquote(&value) 
     from saslib.tl1_results_eval 
     group by plan_cell; 
    %end; 
    quit;                
    %mend;     
    %loop(%str(a,b,c,d)) 

注意proc sql;语句的运动 - 很少有很好的理由退出;并重新实例化每个SQL语句之间的SQL过程,从而导致开销。

+0

您可以扩展这些'好理由'吗?谢谢 – 2014-11-24 19:56:43

+0

要获得每个步骤的计时统计信息,并且还希望在发生错误后执行后续的SQL语句。 – 2014-11-24 20:57:34

+0

工作起来就像一个魅力RawFocus。非常感谢! – 2014-11-25 09:20:43