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

Ready to join fellow brilliant minds for the SAS Hackathon?

Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.

Register today!
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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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