DATA Step, Macro, Functions and more

How to pass more than 2 Macro Variables as KEY to Hash Object

Reply
Super Contributor
Posts: 298

How to pass more than 2 Macro Variables as KEY to Hash Object

I want to pass two or more macro variables as Key to a hash object.

%let KEY = Name Account_Number;

data _null_;

    if _n_ = 1 then do;

      if 0 then set Some_Data_Set;

      declare hash h();

      h.definekey("&KEY");

      h.definedata("&KEY");

      h.definedone();

end;

run;

The following is the error.

ERROR: Undeclared key symbol name account_number for hash object at line 2158 column 7

 

Super User
Posts: 5,516

Re: How to pass more than 2 Macro Variables as KEY to Hash Object

In this case, it would be appropriate for you to do the first half of the work.  Show us what the final program would look like if you were not using macro language, but just hard-coding the whole thing.

SAS Employee
Posts: 24

Re: How to pass more than 2 Macro Variables as KEY to Hash Object

I believe the issue here is syntax. Try setting your macro variable like this:

%let KEY = Name", "Account_Number;

 

definekey and definedata are expecting each key and data variable to be surrounded by quotes and separated by a comma.

PROC Star
Posts: 1,760

Re: How to pass more than 2 Macro Variables as KEY to Hash Object

Posted in reply to michelle_delaurentis_sas_com
%let keys = 'Name', 'Account_Number';
data _null_;
  if _n_ = 1 then do;
    if 0 then set Some_Data_Set;
    declare hash h();
    h.definekey(&keys.);
    h.definedata(&keys.);
    h.definedone();
  end;
run;

would be the clean way to pass those values imho.

Super Contributor
Posts: 298

Re: How to pass more than 2 Macro Variables as KEY to Hash Object

Michelle:

Your solution works. Thank you.

 

ChrisNZ:

Your solution works too. Thanks.

 

I found that the KEY has also to be used in KEEP= SET option. I wanted to use in "data out(keep = &KEY);" . Both your suggestions will

not directly work. I found it convenient to split the KEY into two: 

%let key1 = name;

%let key2 = account_number;

 

then I used

h.definekey("&key1", "&key2");

SAS Employee
Posts: 24

Re: How to pass more than 2 Macro Variables as KEY to Hash Object

I completely agree with ChrisNZ, much cleaner.

 

One additional point...you can use call missing for any variables that are defined as data in the hash if they do not exist anywhere else in the data step, to avoid the warning you get in the log for undefined variables.

Super User
Super User
Posts: 7,074

Re: How to pass more than 2 Macro Variables as KEY to Hash Object

Personally I have a utility macro that I use for things like this.

 

%let KEY = Name Account_Number;
%put %qlist(&key);
('Name','Account_Number')


 h.definekey%qlist(&KEY);
Ask a Question
Discussion stats
  • 6 replies
  • 290 views
  • 2 likes
  • 5 in conversation