Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run part of macro based on number of observations in work file in SAS

I’m pretty new to doing macros on SAS so apologies in advance if my questions seems basic.

I’m looking to execute part of a macro if there are a minimum number of observations found in temporary work file.

If there are a minimum number of observations, the macro should execute a proc export of that temporary work file, otherwise it will just produce an error message on the log.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m not sure what I’m doing wrong, the temporary work file has more than 1 observation and I want the macro to run, however it produces the error message as if it has less than the minimum.

Below is the code that I’ve created so far – any help you have to offer will be greatly welcomed.

data original_data;
set data.dataset;

keep column1 column2 column3 ;
run;


%macro test_macro;

%let dsid=%sysfunc(open(work.original_data));
%let nobs=%sysfunc(attrn(&dsid,nobs));
%let dsid=%sysfunc(close(&dsid));


%if &nobs >1 %then %do;
%put ERROR: No observations counted;
%return
%end

%else %do;

proc export data=submissions
        outfile='C:\Users\myusername\Desktop\test.csv'
        DBMS=csv replace; 
run;

%end;

%mend test_macro;

%test_macro

>Solution :

  1. Missing semicolons on RETURN and END statements
  2. Logic is reversed. You’re putting the error message if you have more than one observation. Flip your code so that you export if you have more than one observation.
  3. Use %EVAL() for comparisons just to be careful. Character comparisons can lead to unexpected results.
options mprint symbolgen;

%macro test_macro;
    %let dsid=%sysfunc(open(work.original_data));
    %let nobs=%sysfunc(attrn(&dsid, nobs));
    %let dsid=%sysfunc(close(&dsid));
    %put &nobs;
    *if more than one observation;

    %if %eval(&nobs > 1) %then
        %do;

            proc export data=sashelp.class outfile='/home/fkhurshed/test.csv' DBMS=csv 
                    replace;
            run;

        %end;
    %else
        %do;
            %put ERROR: No observations counted;
            %return;
        %end;
%mend test_macro;

%test_macro;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading