BookmarkSubscribeRSS Feed
KachiM
Rhodochrosite | Level 12

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

 

6 REPLIES 6
Astounding
PROC Star

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.

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.

ChrisNZ
Tourmaline | Level 20
%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.

KachiM
Rhodochrosite | Level 12

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");

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.

Tom
Super User Tom
Super User

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);

hackathon24-white-horiz.png

The 2025 SAS Hackathon Kicks Off on June 11!

Watch the live Hackathon Kickoff to get all the essential information about the SAS Hackathon—including how to join, how to participate, and expert tips for success.

YouTube LinkedIn

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 6 replies
  • 2747 views
  • 2 likes
  • 5 in conversation