Skip to Main Content

Changing the length of a character variable | SAS Code Fragments

*--------------------------------------------;
* Original Dataset
*
* x has a length of 20 here;
*--------------------------------------------;

data test1;
    length x $20;
    input x $;
    datalines;
abc
def
ghi
jkl
;
run;

proc contents data=test1;
run;

*------------------------------------------------------------------------;
* Change the length of y to 3;
*------------------------------------------------------------------------;

*------------------------------------------------------------------------;
* Solution 1 : length statement;
*
* This solution creates a warning if the new length is shorted than the old one;
*
* WARNING: Multiple lengths were specified for the variable x;
*          by input data set(s). This can cause truncation of data.;
*
* The order of the variables is affected
* if the updated variable is not the first variable and
* no other variable is listed before the set statement; *------------------------------------------------------------------------;

data test2;
    length x $3;
    set test1;
run;

proc contents data=test2;
run;

*------------------------------------------------------------------------;
* Solution 2: options varlenchk=nowarn;
*
* This solution can be considered if no truncation is expected;
*
* The order of the variables is affected
* if the updated variable is not the first variable and
* no other variable is listed before the set statement; *------------------------------------------------------------------------;

options varlenchk=nowarn;
data test3;
    length x $3;
    set test1;
run;
options varlenchk=warn;

proc contents data=test3;
run;

*------------------------------------------------------------------------;
* Solution 3 - Preferred Solution
*              (but when reducing the length of the variable,
*               check the length of the values
*               if you are not sure about them
*               to avoid unexpected truncation)
*
* This solution won't create any warning even if truncation are occurring;
*
* The order of the variables is not affected; *------------------------------------------------------------------------;

proc sql;
    alter table test1
    modify x char(3);
quit;

proc contents data=test1;
run;

We thank Véronique Bourcier from xxformat.com for his comment about the warning created by solution 1 and for his 
solution 2 and 3 to avoid the warning.