SAS: Run SQL-query using a macro

会有一股神秘感。 提交于 2020-04-30 06:31:28

问题


Using an answer from this thread, I was trying to get to work the following code. I have a list of sql-queries in a table plus an id for each query. Now I'd like to have the results of these queries plus the id as another table.

/* The Macro */
%macro run_query(q,id);
  proc sql noprint;
      select count into: count
      from (&q.) a;
  quit;
%mend;

/* Some fake-data */
DATA queries;
INPUT id :$12. query :$3000.;
INFORMAT id $12.;
INFILE DATALINES DSD;
DATALINES;
01,SELECT COUNT(*) AS count FROM sashelp.bweight WHERE Married=1
0101,SELECT COUNT(*) AS count FROM sashelp.bweight WHERE Boy=1
0102,SELECT COUNT(*) AS count FROM sashelp.bweight WHERE Black=1
;
RUN;

/* Make a copy of the dataset */
DATA want;
SET queries;
RUN;

/* Insert the results */
data want;
set queries;
call execute(%nrstr(%run_query('||query||','||id||')));
run;

Can anyone see, what the problem is? The error report looks like this:


回答1:


In part /* Insert the results */ you're basically sending all your values/results into dev null with the data step:

data _null_;

Instead try:

data want;



回答2:


you can try this for the second part

use proc sql in macro to extract the count, and build dataset using variable count1,count2,count3

       %macro a;
    proc sql;
    select count(*) into :count1 FROM sashelp.bweight WHERE Married=1;
    SELECT COUNT(*) into :count2 FROM sashelp.bweight WHERE Boy=1;
    SELECT COUNT(*) into :count3 FROM sashelp.bweight WHERE Black=1;
    quit;

    DATA queries;
    length id $12 query $3000;
    format id $12. query $3000.;
    infile datalines delimiter=','; 
    input id $ query $;
    datalines;
    01,&count1
    0101,&count2
    0102,&count3
    ;
    run;
  %mend a;

/*Call above maco*/
    %a;


来源:https://stackoverflow.com/questions/61340229/sas-run-sql-query-using-a-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!