RETAIN

Christian Baghai
2 min readApr 2, 2021

--

The RETAIN statement determins the initial value for a variable The syntax of the RETAIN statement allows it to specify an ‘initial value’ — i.e. its value at the start of the very first iteration of the DATA step. So we can initialize the variable by assigning a constant value or assigning a value that comes from another variable.

The RETAIN statement retains SAS value in the PDV for the duration of an iteration or multiple iterations. But keep in mind that if the variable has already been defined prior to the RETAIN statement, then RETAIN cannot alter the type or length of the variable

The RETAIN statement can also be used in order to determine the order of the variables of the dataset that results from a data step. When used for this purpose, RETAIN should be placed before any variable is defined and generally should be used without any specification of initial values. In this way, the RETAIN statement does not itself establish the type or length of variables, thereby avoiding the risk of any unwanted errors or conflicts.

If a RETAIN statement attempts to assign an initial character value to a variable already defined as numeric, or vice versa, then an error will occur. This is due to the fact that no implicit conversion take place. This error will result in the data step being terminated.

So, let’s see the through an example.

In this first example we can see that new_var is empty when we want to assign its value to pre_set.

/*data step without retain*/ 
data test2;
pre_set=new_var;
set SASHELP.CLASS;
new_var=Weight * 10;
run;

The solution to that is to use the retain statement. by placing retain new_var before new_var is created, the variable new_var will be set to not missing at the beginning of the data step iteration.

/*data step with retain*/ 
data test1;
retain new_var;
pre_set=new_var;
set SASHELP.CLASS;
new_var=Weight * 10;
run;

In conclusion, retain offer a lot of possibilities. However, the user of the retain statement must be careful of not to fall victim of its subtleties.

--

--