Search code examples
sasenterprise-guidedatastep

sas insert table into html email


Is it possible to loop through the records of a table to populate an html email without repeating the beginning and the end of the email?

With this example I get a mail with 5 tables of 1 row (because WORK.MyEmailTable is table of 5 records and set creates a loop in the data step):

data _null_;
   file mymail;
   set WORK.MyEmailTable;

   put '<html><body><table>';

   ***loop through all records;
   put '<tr>';
   put %sysfunc(cats('<td>',var1,'</td>'));
   put %sysfunc(cats('<td>',var2,'</td>'));
   put %sysfunc(cats('<td>',var3,'</td>'));
   put '</tr>';

   put '</table></body></html>';

run;

And I'm looking to have 1 table of 5 rows.

I don't know if there is a way to prevent recursively put the beginning and the end of the mail when you use set in the data step.

(Let me know if it's not clear I'll update.)

Thank you,


Solution

  • You can use the _n_ automatic datastep variable to let you know when you are on the first observation, and the set statement option end= to know that you are on the last observation:

    data _null_;
        file mymail;
        set WORK.MyEmailTable end=eof;
    
        if _n_ eq 1 then do;
          put '<html><body><table>';
        end;
    
        /*loop trhough all records*/
        put '<tr>';
        put %sysfunc(cats('<td>','_n_=',n,' eof=',eof,' ',var1,'</td>'));
        put %sysfunc(cats('<td>','_n_=',n,' eof=',eof,' ',var2,'</td>'));
        put %sysfunc(cats('<td>','_n_=',n,' eof=',eof,' ',var3,'</td>'));
        put '</tr>';
    
        if eof then do;
          put '</table></body></html>';
        end;
    run;
    

    I've added the values _n_ and eof to the output so you can see clearly how they work.