I'm trying to take a long list and concatenate it into a long string/list, that I can store in a macro variable.
For instance:
I'd like to turn a dataset with a set of phone numbers like:
ID Phone
1 1234567890
2 4634069845
3 9438758375
4 2349853984
5 3459086098
6 6689476988
7 3030495986
8 3459495954
...into a macro variable that looks like:
'1234567890', '4634069845', '9438758375', '2349853984', '3459086098', '6689476988', '3030495986', '3459495954'
Say we'll call it &PhoneString, then I can later create a sql query that looks like:
select * from applications
where phone in (&PhoneString).
Thanks!
@anthdelm wrote:I'm trying to take a long list and concatenate it into a long string/list, that I can store in a macro variable.
For instance:
I'd like to turn a dataset with a set of phone numbers like:
ID Phone
1 1234567890
2 4634069845
3 9438758375
4 2349853984
5 3459086098
6 6689476988
7 3030495986
8 3459495954
...into a macro variable that looks like: /* look into sql into clause for creating macro vars separated by a delimiter in sas docs. the answer is in your question*/
'1234567890', '4634069845', '9438758375', '2349853984', '3459086098', '6689476988', '3030495986', '3459495954'
Say we'll call it &PhoneString, then I can later create a sql query that looks like:
select * from applications
where phone in (&PhoneString).
Thanks!
proc sql noprint;
select quote(PhoneNumber)
into :PhoneList separated by ","
from PhoneList;
quit;
Note the macro variable PhoneList is limited to 32K characters in length.
data cntlin;
set phone_numbers (keep=phone rename=(phone=start)) end=done;
type = 'C';
fmtname = "select_phone";
length label $10;
label = 'yes';
output;
if done
then do;
label = 'no';
start = '**OTHER**';
hlo = 'O';
output;
end;
run;
proc sql;
select * from applications where put(phone,$select_phone.) = 'yes';
quit;
Using a format avoids problems with macro variable overflows, and creates short code even with options mprint active. Your only limit is your available memory for loading the format. And that is much higher than the 32767 of a macro variable.
data have;
input ID Phone$;
datalines;
1 1234567890
2 4634069845
3 9438758375
4 2349853984
5 3459086098
6 6689476988
7 3030495986
8 3459495954
;
proc sql noprint;
select quote(Phone,"'") into :PhoneNums separated by ',' from have;
run;
%put &PhoneNums.;
Would change
select * from applications
where phone in (&PhoneString)
into
select * from applications
where phone in (select phone from phoneNumbers)
Another nice solution that avoids creating an unwieldy macro variable.
Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.
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.