Below is code that produces a quoted string from a column in a dataset. This can be used in an IN-statement in SQL.
proc sql; select quote(Compress(name)) into :SQLMetaSrc separated by ',' from datasets ; quit;
Below is code that produces a quoted string from a column in a dataset. This can be used in an IN-statement in SQL.
proc sql; select quote(Compress(name)) into :SQLMetaSrc separated by ',' from datasets ; quit;
The SAS SQL-statement below will create a dataset containing all information for the observation with the lowest age in the dataset SASHELP.CLASS.
proc sql; create table CLASS as select * from SASHELP.CLASS group by AGE having AGE=min(AGE) ; quit;
The syntax for the SAS SQL-statement is showed below.
proc sql; create table <DESTINATION TABLE> as select * from <SOURCE TABLE> group by <COLUMN TO SEARCH> having <COLUMN TO SEARCH>=<FUNCTION>(<COLUMN TO SEARCH>) ; quit;
As you see the <FUNCTION> doesn’t have to be min (minimum), it can be any function working on the type of <COLUMN TO SEARCH> – numeric or char.
The code below lets you qoute the contant of a macrovariables e.g. to be used in an IN SQL-statement.
%let Variables = age height weight; %let InStatement = %Str(%’)%sysfunc(Tranwrd(&Variables.,%Str( ),%Str(%’, %’)))%Str(%’);
The macrovariable InStatement will contain ‘age’,’height’,’weight’. And can then be used in an IN SQL-statement.
There are different possibilities when you need to quote a string in SAS.
Before you read any further! Instead of using ‘ ‘ around the macro-variable use “ “.
The SQL-statement below will not work.
proc sql noprint;
insert into ToLib.DestDataset
select *
from FromLib.SourceDataset
where Year = ‘&Year.’;
quit;
The SQL-statement below will work.
proc sql noprint;
insert into ToLib.DestDataset
select *
from FromLib.SourceDataset
where Year = “&Year.”;
quit;
If you have a macro variable containing a year that could be 2012, and you need to put ‘ ‘ or “ “ around it, you can use the macro-functions %bquote as shown below.
My program works like this. I retrieve a year variable into a macro-variable from a configuration dataset.
proc sql noprint;
select upcase(Value) into :Year
from Config.Config_data
where upcase(Name) = upcase(‘Year’);
quit;
I remove blanks (if any)
%let Year = %trim(&Year.);
When I tried to quote the macro-variabel Year (it’s a string not a numeric) to get Year = ‘2012’ I got and error
proc sql noprint;
insert into ToLib.DestDataset
select *
from FromLib.SourceDataset
where Year = %bquote(‘&Year.’);
quit;
I found out that I needed to trim the %bquote-statement again. When I did that it worked.
proc sql noprint;
insert into ToLib.DestDataset
select *
from FromLib.SourceDataset
where Year = %trim(%bquote(‘&Year.’));
quit;
Another way to solve this would be to use
proc sql noprint;
select upcase(Value) format=$quote40. into :Year
from Config.Config_data
where upcase(Name) = upcase(‘Year’);
quit;
This will put “” around the year like “2012”.