Hello,
I would like to know if there is a way to add a new variable to an existing dataset without creating the updated dataset (i,e, the existing dataset with the new variable added).
I would like to know if there is a way add a new variable but without having to create the dataset
see code below:
%macro VarExist(dsn=,varname=);
%let dsn2=&dsn.;
%local dsid vnum;
%let vnum=0;
%let dsid = %sysfunc(open(&dsn));
%if &dsid %then %do;
%let vnum = %sysfunc(varnum(&dsid,&varname));
%let dsid = %sysfunc(close(&dsid));
%end;
&vnum
%mend ;
data test;
set sashelp.class;
run;
%if %varexist(dsn=test,varname= New_Variable ) = 0 %then
%do;
data &dsn2.;
%put &=dsn2.;
attrib New_Variable label="New Variable" length=$5. format=$5. informat=$5.;
set &dsn2.;
run;
%end;
Adding a variable changes the observation length; since observations always occupy a contiguous space, the dataset needs to be rewritten.
Can you describe your question a bit more?
If you want to add a variable to an existing dataset, then by definition that dataset will be updated (actually over-written) when you add a variable to it.
in the SAS code, more precisely at the if condition,
I am using an attribute statement with a set statement to update the dataset as below.
%if %varexist(dsn=test,varname= New_Variable ) = 0 %then
%do;
data &dsn2.;
%put &=dsn2.;
attrib New_Variable label="New Variable" length=$5. format=$5. informat=$5.;
set &dsn2.;
run;
%end;
I wonder if it could be possible to add a new variable with the dataset identifier
as below and if so, how do we do that.
%let dsid = %sysfunc(open(&dsn));
%if &dsid %then %do;
adding the new variable with its name, label and format.
%let dsid = %sysfunc(close(&dsid));
Ahh, I see. It's always risky to say "no" when someone asks if it's possible to do something in SAS, but I don't think you can use the metadata functions for adding variables. In order to add a variable to a dataset, SAS has to rewrite the dataset (header metadata and data). That is a job for the DATA step.
If by tiny chance your goal is to write a function-style macro that would add variables to a dataset, that would be possible (using DOSUBL) but it would still use a DATA step.
Adding a variable changes the observation length; since observations always occupy a contiguous space, the dataset needs to be rewritten.
As @Kurt_Bremser has stated, anytime you add or drop columns from a SAS dataset, you need to add or remove the space to hold it even if it contains only missing values. Changing just the descriptor portion of a SAS dataset is not possible when it involves adding or dropping columns.
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
Check out this tutorial series to learn how to build your own steps in SAS Studio.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.