Hi all, I want to export multiple csv files (by gender) from one sas dataset. My code below works to create the files, however I can't figure out how to keep the column names in the exported files. Please help!
Note: I am using the sashelp.class dataset for my code below
data _null_; set class; length fv $ 200; fv = "C:\Users\abi\Desktop\Output" || TRIM(put(sex,4.)) || ".csv"; file write filevar=fv dsd dlm=',' lrecl=32000; put (_all_) (:);; run;
Is the source data sorted by the variable used to split?
If so use BY group processing to decide when to write the header row.
%let path=%sysfunc(pathname(work));
proc sort data=sashelp.class out=class;
by sex;
run;
data _null_;
set class;
by sex ;
fv=cats("&path/",sex,'.csv');
file csv filevar=fv dsd ;
if first.sex then put "NAME,SEX,AGE,HEIGHT,WEIGHT";
put (_all_) (+0);
run;
Otherwise create the files with the header rows first then use the MOD option on the FILE statement in your step that writes the data lines.
proc contents data=class noprint out=names(keep=varnum name label);
run;
proc sql;
create tables headers as
select distinct a.*,cats("&path/",b.sex,'.csv') as fv
from names a
, class b
order by fv, varnum
;
quit;
data _null_;
set headers;
file out dsd filevar=fv ;
put name @ ;
run;
data _null_;
set class;
fv=cats("&path/",sex,'.csv');
file csv filevar=fv dsd mod;
put (_all_) (+0);
run;
Is the source data sorted by the variable used to split?
If so use BY group processing to decide when to write the header row.
%let path=%sysfunc(pathname(work));
proc sort data=sashelp.class out=class;
by sex;
run;
data _null_;
set class;
by sex ;
fv=cats("&path/",sex,'.csv');
file csv filevar=fv dsd ;
if first.sex then put "NAME,SEX,AGE,HEIGHT,WEIGHT";
put (_all_) (+0);
run;
Otherwise create the files with the header rows first then use the MOD option on the FILE statement in your step that writes the data lines.
proc contents data=class noprint out=names(keep=varnum name label);
run;
proc sql;
create tables headers as
select distinct a.*,cats("&path/",b.sex,'.csv') as fv
from names a
, class b
order by fv, varnum
;
quit;
data _null_;
set headers;
file out dsd filevar=fv ;
put name @ ;
run;
data _null_;
set class;
fv=cats("&path/",sex,'.csv');
file csv filevar=fv dsd mod;
put (_all_) (+0);
run;
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.