TIP00410

%macro getVarType( _sasdsn_=, _varname_=,);
   /*** getVarType macro
     Author: Charles Patridge
     Its purpose is to determine the Attribute Type of any SAS Variable within
     the SAS Dataset specified.
     1st parameter - _sasdsn_  - is name of SAS Dataset to search for the variable
     2nd parameter - _varname_ - is name of SAS variable to determine its type

     This macro will create a global macro variable named the same as the variable
     in the 2nd parameter with "_Type" added to its name as a suffix;
     for example, if variable given as 2nd parameter is "salary", the created macro 
     name will be "salary_Type"

     The values of created macro variable will be 
          "C" - Character
          "N" - Numeric
          ""  - variable given as 2nd parameter Does NOT EXIST (DNE) within the SAS Dataset
                in the 1st parameter.

     This macro can be called on its own or within a DataStep - however it is more
     efficent if called on its own as a SAS variable can NOT change its type within 
     a SAS Dataset.
   ***/

 %let dsid=%sysfunc(open(&_sasdsn_,i));
 %global &_varname_._Type;
 %let    &_varname_._Type = ;
 %do i=1 %to %sysfunc(attrn(&dsid,nvars));
    %if %upcase(&_varname_) = %upcase(%sysfunc(varname(&dsid,&i))) %then %do;
        %let &_varname_._Type = %sysfunc(vartype(&dsid,&i));
		%goto _alldone_;
	%end;
 %end;
 %_alldone_: %let rc=%sysfunc(close(&dsid));
 %mend getVarType;
 
/*** example use of macro ***/
/*** 

 libname  mylib    'c:\download\sas_salary\'; run;
%let mysasfile = mylib.sasalary;

       %getVartype( _sasdsn_=mylib.sasalary, _varname_=salary);

        data test;
         set mylib.sasalary;
         *** determine if salary is Numeric, Character, or Does Not Exist at all;

         salary_type = "&salary_Type" ;

              if salary_Type = "N" then flag = "Numeric   ";
         else if salary_type = "C" then flag = "Character ";
         else                           flag = "DNE       ";
        run;
***/
/*** end of TIP 00410 ***/