1
votes

I am new to SAS and didn't find an answer to my question. Maybe this community would/could be so Kind to help me.

Is it possible to define the value of a macro variable as the length of another variable? I do know that the value of a macro is character, but is there a way to do is?

My Problem is this: I want to check my variable for the longest value and set the length of the longest value as a new length for the variable. Therefore I used this program:

proc sql;

select max(length(variable))

into: length_variable

from dm_comp;
quit;

%put length_variable;

Now I have the value as character in my macro, but I don't know how to use this macro to set a new length. Is it even possible to do this way? If not, do you have an idea how to do it better? Thank you very much for your help.

2

2 Answers

2
votes

You can use a Data Step to redefine the variable and populate it from the old Data Set.

/*Data with variable length 10, only need 2*/
data temp;
length x $ 10;
x="1";
output;
x="11";
output;
run;

proc sql noprint;
select max(length(x))
    into: length_variable
from temp;
quit;

/*Puts 2 as expected*/
%put &length_variable;

/*First define the variable and the new length,
  Then "set" the Data step - rename the old variable.
  Set the new variable to the old one (I strip whitespace here)*/
data temp(drop=x_old);
length x $ &length_variable;
set temp(rename=(x=x_old));
x = strip(x_old);
run;

/*CONTENTS Show us the new length*/
proc contents data=temp;
run;

Results

                  Alphabetic List of Variables and Attributes

                         #    Variable    Type    Len

                         1    x           Char      2
0
votes

You're on the right track. You just need to format the new variable correctly:

proc sql;
    select max(length(variable))
    into: length_variable
    from dm_comp;
quit;

proc sql;
    create table dm_comp2 as select
        *, your_var as resized_var format %sysfunc(strip(&length_variable.)).
        from dm_comp;
quit;