Let's see an example.
data test;do gender='F','M';output;end;run;data _null_;set test;call execute(cat('data class_',gender,';set sashelp.class;where sex="',gender,'";run;'));run;
With running this code, SAS doing three things:
F
and the 2nd row is M
;data _null_
, SAS parses argument of call execute
, and stores the result of parsing in memory, then over the data _null_
setp;data class_F;set sashelp.class;where sex="F";run;data class_M;set sashelp.class;where sex="M";run;
Now you can see data class_F and class_M are lying in work library.
Even more surprising, you can use call execute
conditionally because it is a routine, this may help you design more complex and flexible program.
As for you question, I think it is easy now for you to get the following solution:
data codebook_edit;set codebook end=eof;format Syntax_Label $2000.;Syntax_Label=cat(trim(Field_Name), " = '", trim(Field_Label), "'");if _n_=1 then call execute('data _null_; set codebook_edit; label ');call execute(Syntax_Label);if eof then call execute('; run;');run;
I also move your keyword label
into the 1st call execute
to make code clean.
And an alternative approach entirely.Instead of generating the multiple label statements create a data set that has the old label and new label. Read those into a macro variable and then apply them.
*Create label data set;data label_data_set;length name label $25.;name="Sex"; label="Gender"; output;name="height"; label="Height (in)"; output;name="weight"; label="Weight (lbs)"; output;run;*Create sample dataset to apply label;data class;set sashelp.class;run;*Create macro variable that holds label statement;proc sql noprint;select catx("=", name, quote(trim(label)))into :label_list separated by " "from label_data_set;quit;*Display macro variable in log;%put &label_list.;*Apply labels without recreating dataset;proc datasets library=work;modify class;label &label_list.;run;quit;*Print the dataset to display new labels;proc print data=class label noobs;run;
You can use a similar methodology for renaming or applying formats.And applying these using PROC DATASETS is more efficient than a new data step as it doesn't recreate the data, just updates the metadata.