Warm tip: This article is reproduced from serverfault.com, please click
sas

Using SAS' proc sql or data step to replace the value of a single cell in a table?

发布于 2020-12-03 10:41:03

Probably I am simply using the wrong search terms: I have a large table have with multiple columns (e.g. x, y, z) and various rows, and I intend to replace a single value within with a value I have saved in a macro variable called new_value.

Reading out the current value old_value of the respective cell is straight forward:

%let new_value = 4711;
proc sql noprint;
   select z into: old_value
   from have
   where x = 42 and y = 21;
quit;
%put --- f(42,21) = &old_value. ---;

How do I update the column z for those cases where x=42 and y=21 with &new_value?

I would also happy with a data step if it is resasonably fast. I would like to just modify the table, and not create a new one, because the table is really huge.

References

Questioner
B--rian
Viewed
0
crow16384 2020-12-03 19:00:29

Let's do temporary copy of SASHELP.CLASS data for performing an exercise.

data class;
  set sashelp.class;
run;

Select one string value

%let new_value=90;
proc sql noprint;
   select weight into :old_value from class where name='Thomas' and Age=11;
quit;
%put --- f(Tomas,11) = &old_value. ---;

Update in SQL is pretty simple, you have got conditions:

proc sql;
  update class set weight=&new_value where name='Thomas' and Age=11;
quit;

PROC SQL could be used for update more than one table via VIEW, but it's another question.

In the data step you can use transactions (but data sorting is required, which is not free). Let work with initial copy of CLASS dataset:

proc sort data=class;
  by name sex age;
run;

Prepare example transaction data (could be more then one records):

data transaction;
  set class;
  where name='Thomas';
  weight=&new_value;
run;

proc sort data=transaction;
  by name sex age;
run;

And make update:

data class;
  update class transaction;
  by name sex age;
run;

Keys name, sex and age here are just for example.