2016-12-11 87 views
0

我想創建一個向數據集中的變量名添加後綴的宏。下面是我的代碼:SAS:創建一個爲數據集中的變量添加後綴的宏

%macro add_suffix(library=,dataset=,suffix=); 
    proc sql noprint; 
     select cat(name, ' = ', cats('&suffix.',name)) into :rename_list separated by ' ' from 
     dictionary.columns where libname = '&library.' and memname= '&dataset.'; 
    quit; 

    proc datasets library=&library nolist nodetails; 
     modify &dataset; 
     rename &rename_list; 
    run; 

    quit; 

%mend; 
%add_suffix(library=OUTPUT,dataset=CA_SPREADS,suffix=CA); 

它提供了錯誤信息:

NOTE: No rows were selected. 
NOTE: PROCEDURE SQL used (Total process time): 
     real time   0.00 seconds 
     cpu time   0.00 seconds 


WARNING: Apparent symbolic reference RENAME_LIST not resolved. 
NOTE: Line generated by the invoked macro "ADD_SUFFIX". 
2             rename &rename_list;  run; 
                 - 
                 22 
                 76 
NOTE: Enter RUN; to continue or QUIT; to end the procedure. 

ERROR 22-322: Expecting a name. 

ERROR 76-322: Syntax error, statement will be ignored. 

如果我把引號庫和數據集的名字,它的工作原理對於第一塊即值添加到字符串rename_list但不對於PROC數據集的步驟

+0

看起來您正在嘗試添加名稱的前綴。 – Tom

+0

這裏沒有考慮到,但你需要確保名稱長度不超過32個字符。對於重命名部分,我更喜歡CATX,閱讀起來更清晰。 https://gist.github.com/statgeek/82d9f2854edc01560e0f – Reeza

回答

2

宏觸發器如%&在單引號內不受尊重。這就是爲什麼你沒有得到任何關於你的SQL查詢的命中。沒有一個名稱爲&的庫名稱作爲第一個字符。

它看上去就像是那種工作的原因是,當你使用這個在您的SQL語句

catx('=',name,cats('&prefix.',name)) 

那麼你最終像

age=&prefix.age 

一個字符串,這將實際因爲在運行RENAME語句時,對宏變量PREFIX的引用將會解決。

您應該使用雙引號代替。

%macro change_names(library=,dataset=,prefix=,suffix=); 
%local rename_list; 
proc sql noprint; 
    select catx('=',name,cats("&prefix",name,"&suffix")) 
    into :rename_list separated by ' ' 
    from dictionary.columns 
    where libname = %upcase("&library") 
    and memname = %upcase("&dataset") 
    ; 
quit; 

%if (&sqlobs) %then %do; 
proc datasets library=&library nolist nodetails; 
    modify &dataset; 
    rename &rename_list; 
    run; 
quit; 
%end; 
%else %put WARNING: Did not find any variables for &library..&dataset..; 
%mend change_names; 

%change_names(library=OUTPUT,dataset=CA_SPREADS,prefix=CA); 
1
  1. 你的宏觀變量沒有被解決,因爲你包裹在他們的單引號',而不是雙引號"
  2. 您應該大寫宏的libname和memname參數,因爲它們在dictionary.columns中始終爲大寫。
1

經過測試和工作。更長,但也許更多初學者友好的方法。輸入數據集名稱和要添加的後綴。

示例:%add_suffix(orders,_old);/*將爲所有變量添加_old後綴*/

%macro Add_Suffix(Dataset, suffix); 
    proc contents noprint 
     data=work.&dataset out=sjm_tmp(keep=NAME); 
    run; 

    data sjm_tmp2; 
     set sjm_tmp; 
     foobar=cats(name, '=',NAME,'&suffix.'); 
    run; 

    proc sql noprint; 
     select foobar into :sjm_list separated by ' ' from sjm_tmp2; 
    quit; 

    proc datasets library = work nolist; 
     modify &dataset; 
     rename &sjm_list; 
    quit; 

    proc datasets library=work noprint; 
     delete sjm_tmp sjm_tmp2 ; 
    run; 
%mend Add_Suffix;