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
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.
%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.
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.
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);
⏰
Today is the last day to save with the early bird rate! Register today for just $695 - $100 off the standard rate.
Plus, pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.
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.