ZIPCOUNTYNM Function

Here's a simple but very useful example of how to write a table lookup function using a hash object.  SAS Institute provides a zipcode-level dataset that associates a (primary) county name with each zip code.  I developed the following user-written SAS function and call it ZIPCOUNTYNM.  When you call the function, you provide it with a five-digit numeric zip code and it returns the name of the county associated with that zip code.

**************************************;
* Program Name: ZIPCOUNTYNM Function *;
* Last Updated: 03/13/15 by David Oesper      *;
**************************************;
proc fcmp outlib=work.funcs.zipcountynm;
   function zipcountynm(zip) $13;

      length countynm $13;
      declare hash h(dataset:"sashelp.zipcode");
         rc = h.definekey("zip");
         rc = h.definedata("countynm");
         rc = h.definedone();
         call missing(countynm);
         rc = h.find();
      return(countynm);
   endsub;
run;

options cmplib=(work.funcs);

data _null_;
   zip = 50010;
   countynm = zipcountynm(zip);
   put zip= countynm=;
run;

proc fcmp outlib=work.funcs.zipcountynm;
   deletefunc zipcountynm;
run;

And here's a SAS log illustrating the use of this program.



Note: if you wish to design a function y = f(x) where x is a character value, then you will need to code a $ on the function statement as follows:

function y(x$);