Search code examples
sassas-macro

How to delete and import datasets dynamically in SAS?


I have four comma separated files: mar2009.txt, mar2010.txt, mar2011.txt and mar2012.txt

I am trying to cleanse my library and import those datasets dynamically:

libname my "C:\Users\Owner\Desktop\SAS\";

data A; // I do not this step but if I do not use it the the "do" becomes red in color
do i = 2009 to 2012;

proc datasets library=my;
delete mar.&i;
run;

proc import out=my.mar.&i datafile="C:\Users\Owner\Desktop\SAS\mar.&i.txt" dbms=dlm replace;
delimiter='2c'x;
getnames=yes;
datarow=2;
run;

end;
run;

Solution

  • To answer your question at a fundamental level, you don't need to "cleanse" the dataset just because you are reimporting it; it will automatically be replaced.

    You could write a macro to do the import, like so:

    %macro import_myfile(i=);
    proc import file="...whatever...\mar&i.txt" out=mar_&i. dlm=',' replace;
    run;
    %mend import_myfile;
    
    %import_myfile(i=2009);
    %import_myfile(i=2010);
    %import_myfile(i=2011);
    %import_myfile(i=2012);
    

    You could write a loop to execute that from 2009 to 2012, but it's not worth the code if it's just four runs. If you have a dynamic number to execute, and those values are in a dataset, you could do it this way:

    data data_torun;
    input filenum;
    datalines;
    2009
    2010
    2011
    2012
    ;;;;
    run;
    
    proc sql;
    select cats('%import_myfile(i=',filenum,')') into :listtorun 
     separated by ' '
     from data_torun;
    quit;
    
    &listtorun.;
    *this will become the same four calls as above;
    

    It is typically better to have data like this kept in dataset form rather than in code when it potentially could change (even in a loop). That way you could store this in a text file and read it in.