Macro programming is everywhere in the SAS world. Whether you use macro variables to avoid hard-coding values, macro definitions to package reusable logic, or data-driven techniques to generate dynamic programs, the macro facility is one of the most important tools for writing flexible and maintainable SAS code. That does not change when you move to SAS Viya.

In SAS Viya, most macro code that ran in SAS 9 continues to work without modification because submitted code passes through the compute server, where the macro facility is available. Macro references are resolved before the generated SAS code compiles, so macro variables, macro definitions, macro functions, loops, and conditional logic can still be used to build the code you want to submit.

The important distinction appears when the generated code is intended to run on the CAS server. CAS is designed for distributed, in-memory processing, but it does not interface directly with the macro facility. This means macro logic can still generate CAS-enabled code, but certain data-driven macro programming patterns need a different approach when the data being read lives in CAS.

In this post, we will identify the common situations where macro code needs to be adjusted for CAS, show why those situations occur, and present simple solutions that preserve the intent of the original program.

When you submit SAS code in Viya, the code is processed through the compute server. As a result, macro processing happens in the compute environment before the resulting SAS statements are executed. This is true whether the final data processing occurs on the compute server or whether the generated code submits actions or procedures that interact with CAS.

For example, a program might use a macro variable to store a library name, a table name, a column list, or a filter value. It might also define a macro that produces a larger block of SAS code. In these cases, the macro facility resolves the macro references and produces standard SAS statements. If those statements are valid for the environment where they run, the macro code itself does not need special treatment.

This is the key point: macros generate text. They do not process data directly. If the macro-generated text is submitted from compute and is valid SAS code, it can continue to be used as part of a Viya program.

To illustrate, let’s look at a simple example where macro variables resolve before the procedure runs. The same macro logic is used first with a compute-side table and then with a CAS table.

01  options msglevel=i;
02
03  %let data=work.bigorders;
04  %let country=Singapore;
05
06  title "Order Statistics for &country";
07  title2 "Dataset:  &data";
08  proc means data=&data n mean min max ;
09      var Quantity RetailPrice Cost ;
10      where Country="&country";
11  run;
12  title;
13
14
15  %let data=casuser.bigorders;
16  %let country=Singapore;
17
18  title "Order Statistics for &country";
19  title2 "Dataset:  &data";
20  proc means data=&data n mean min max ;
21      var Quantity RetailPrice Cost ;
22      where Country="&country";
23  run;
24  title;

In this example, the macro variables on lines 3–4 and 15–16 are resolved by the macro facility before PROC MEANS runs. The first PROC MEANS step reads work.bigorders and executes on compute, while the second reads casuser.bigorders and executes on CAS. The macro facility behaves the same way in both cases: it substitutes the values of &data and &country on the compute server into the submitted SAS code before execution begins.

The issue usually appears when a program reads data from CAS and attempts to use the result to populate a macro variable.

In traditional SAS programming, two common techniques are used for reading data into a macro variable: the INTO clause in PROC SQL and CALL SYMPUTX in a DATA step. Both are useful ways to move values from data into a symbol table.

That pattern changes when the source table is processed in CAS. Because CAS does not communicate directly with the macro facility, code running in CAS cannot directly create or update macro variables. The practical result is that programs using PROC SQL INTO or CALL SYMPUTX against CAS-resident data need to be revised.

Fortunately, the solutions are straightforward. The basic idea is to use CAS to perform resource-intensive tasks such as summarizing data. Save the results into a small table that can then be returned to the compute server and used to create a macro variable.

A common SAS 9 approach is to use PROC SQL with an INTO clause to place a value from a query result into a macro variable. The following example illustrates this approach.

01  %let country=Germany;
02  proc sql noprint ;
03      select  mean(RetailPrice), Max(RetailPrice),Min(RetailPrice)
04      into :avgRP, :maxRP, :minRP
05      from work.bigorders
06      where country="&country";
07  quit;
08
09  title "Order Types in &country";
10  proc freq data=work.bigorders;
11      table orderType;
12      where country="&country";
13      footnote "Statistics for Retail Price";
14      footnote2 "Mean: &avgRP, Maximum: &maxRP, Minimum: &minRP";
15  run;

This program uses the value of country to run two steps for Germany. Lines 2–7 calculate the average, maximum, and minimum RetailPrice values and save them in the macro variables avgRP, maxRP, and minRP. Lines 9–15 then run PROC FREQ on the same data and use those macro variable values in footnote2.

Relevant log excerpt

NOTE: PROCEDURE SQL used (Total process time):
real time          16.37 seconds
cpu time           8.36 seconds
 
NOTE: There were 6281550 observations read from the data set WORK.BIGORDERS.
WHERE country='Germany';
 
NOTE: PROCEDURE FREQ used (Total process time):
real time          16.09 seconds
cpu time           8.12 seconds

Note that it took over 30 seconds combined to execute PROC SQL and PROC FREQ. The resulting outputs provide the desired result by adding custom statistics from the data into the footnote:

Output excerpt

Order Types in Germany
OrderType Frequency Percent Cumulative Frequency Cumulative Percent
Catalog Sale 778650 12.40 778650 12.40
Internet Sale 560400 8.92 1339050 21.32
Retail Sale 4942500 78.68 6281550 100.00

Statistics for Retail Price

Mean: 157.2914, Maximum: 6257.2, Minimum: 0.63

The result is correct, but this version does all the work against the compute-side WORK.BIGORDERS table. If the data is also available in CAS, it makes sense to rewrite the program to take advantage of the in-memory and parallel processing capabilities of CAS when creating the macro variable and creating the final summary report. The revised version keeps the same reporting goal but shifts the expensive data processing work to CAS. The code below shows one way to make that adjustment.

01  %let country=Germany;
02
03  proc sql noprint;
04      select  mean(RetailPrice), Max(RetailPrice),Min(RetailPrice)
05      into :avgRP, :maxRP, :minRP
06      from casuser.bigorders
07      where country="&country";
08  quit;
09
10  title "Order Types in &country";
11  proc freqtab data=casuser.bigorders;
12      table orderType;
13      where country="&country";
14      footnote "Statistics for Retail Price";
15      footnote2 "Mean: &avgRP, Maximum: &maxRP, Minimum: &minRP";
16  run;

In this version, the first change is that PROC SQL now reads from the CAS-resident table casuser.bigorders instead of the compute-side work.bigorders when creating the macro variables. The second change is that PROC FREQ has been replaced with PROC FREQTAB, the CAS-enabled version of the procedure. These changes are meant to let the program use the in-memory table and shift more of the processing work to CAS, but the PROC SQL step does not behave as you might expect. The log excerpt below shows what happens when this version runs.

Relevant log excerpt

NOTE: The where clause is being processed by Cloud Analytic Services.
ERROR: The maximum allowed bytes (104857600) of data have been fetched from Cloud Analytic Services. Use the DATALIMIT option to increase the maximum value.
NOTE: PROC SQL set option NOEXEC and will continue to check the syntax of statements.
NOTE: The SAS System stopped processing this step because of errors.
NOTE: PROCEDURE SQL used (Total process time):
real time          5.92 seconds
cpu time           1.75 seconds

This log shows the key problem. The WHERE clause is processed by CAS, but PROC SQL is not supported in CAS, so the query itself must run on the compute server. The compute server tries to pull the matching rows back from CAS, and with a large CAS table that transfer hits the DATALIMIT setting (104,857,600 bytes) before the macro variables are created.

Note that moving data from CAS back to compute is not always a problem. If we were dealing with a smaller subset (e.g., %let data=Singapore), we would not have reached the datalimit and PROC SQL would have successfully moved the data back to compute and created the macro variables.

So how do we process data in CAS and still store information in a macro variable? Let’s look at an alternative solution.

01  %let country=Germany;
02
03  proc fedsql sessref=mySession;
04      create table casuser.rpstats as
05      select  mean(RetailPrice), Max(RetailPrice),Min(RetailPrice)
06      from casuser.bigorders
07      where country=%tslit(&country);
08  quit;
09
10  proc sql;
11      select mean, max, min
12          into :avgRP, :maxRP, :minRP
13          from casuser.rpstats;
14  quit;
15
16  %put _USER_;
17
18  title "Order Types in &country";
19  proc freqtab data=casuser.bigorders;
20      table orderType;
21      where country="&country";
22      footnote "Statistics for Retail Price";
23      footnote2 "Mean: &avgRP, Maximum: &maxRP, Minimum: &minRP";
24  run;

In this revised version, FEDSQL is used to summarize the data because it is supported natively in CAS. However, FEDSQL does not support the INTO clause, so the summary statistics are first written to a small CAS table, casuser.rpstats. Because that table contains only the summarized result, it is small enough to return to the compute server when PROC SQL reads it. The INTO clause in PROC SQL then creates the macro variables needed on compute.

Note also that Line 7 uses %TSLIT(&country) to resolve the macro variable first and then wrap its value in single quotes. Coding “&country” directly into the WHERE in PROC FEDSQL would have resulted in an error because double quotes are not supported for string values.

Relevant log excerpt

FEDSQL step
NOTE: FEDSQL: Running on CAS due to "sessref".
NOTE: Added action set 'fedsql'.
NOTE: CAS action completed [OKAY]
NOTE: Table RPSTATS was created in caslib CASUSER with 1 rows returned.
NOTE: CAS action completed [OKAY]
NOTE: PROCEDURE FEDSQL used (Total process time):
real time          0.80 seconds
cpu time           0.03 seconds
 
...
 
PROC SQL step
NOTE: PROCEDURE SQL used (Total process time):
real time          0.04 seconds
cpu time           0.03 seconds
 
%PUT output
GLOBAL AVGRP 157.29143364
GLOBAL COUNTRY Germany
GLOBAL MAXRP        6,257
GLOBAL MINRP            1
 
...
 
PROC FREQTAB step
NOTE: The where clause is being processed by Cloud Analytic Services.
NOTE: The Cloud Analytic Services server processed the request in 0.91684 seconds.
NOTE: PROCEDURE FREQTAB used (Total process time):
real time          0.97 seconds
cpu time           0.06 seconds

This log confirms that the revised program shifts the significant work to CAS. FEDSQL runs on CAS because of the SESSREF option, creates the one-row RPSTATS summary table, and finishes in less than a second. PROC SQL then reads only that small summary table to create the macro variables on compute. The %PUT output confirms that those macro variables exist in the global symbol table before PROC FREQTAB runs. Finally, PROC FREQTAB processes the CAS table and creates the report, also completing in less than a second.

The same principle applies to DATA step logic that uses CALL SYMPUTX. CALL SYMPUTX is designed to assign a DATA step value to a macro variable, but that assignment occurs in the macro facility on the compute server. If the DATA step executes in CAS, it cannot update the compute-side macro symbol table directly.

The revised approach is to use CAS to write the needed value to a small table, move or access that result from compute, and then run a compute-side DATA _NULL_ step with CALL SYMPUTX to create a macro variable.

Let’s look at a specific example, all of which executes on the compute server.

%let country=Germany;
 
data _null_;
set work.bigorders end=last;
where country="&country";
if ordertype='Retail Sale' then retail+1;
if last then do;
if retail>0 then do;
call symputx('subtitle',catx(" ", "&country has",
put(retail,comma12.), "retail orders."));
end;
else call symputx('subtitle',"&country has no Retail Orders");
end;
run;
 
title "Order Statistics for &country";
title2 "&subtitle";
proc means data=work.bigorders n mean min max ;
var Quantity RetailPrice Cost ;
where Country="&country";
run;
title;

This original program reads work.bigorders on the compute server and uses a DATA step to count the number of retail orders for the selected country and then creates an appropriate subtitle for the report. If at least one retail order is found, the DATA step writes a message to the macro variable subtitle that includes the country name and the formatted order count. If no retail orders are found, it writes a different message indicating that the country has no retail orders. That macro variable is then used as the second title in the PROC MEANS output, making the report title reflect what was found in the data. The log for Germany is displayed below.

Relevant log excerpt

NOTE: There were 6281550 observations read from the data set WORK.BIGORDERS.
WHERE country='Germany';
NOTE: DATA statement used (Total process time):
real time          15.00 seconds
cpu time           7.79 seconds
 
NOTE: Multiple concurrent threads will be used to summarize data.
NOTE: There were 6281550 observations read from the data set WORK.BIGORDERS.
WHERE Country='Germany';
NOTE: PROCEDURE MEANS used (Total process time):
real time          15.03 seconds
cpu time           7.88 seconds

Output excerpt

Order Statistics for Germany

Germany has 4,942,500 retail orders.

Variable N Mean Minimum Maximum
Quantity 6281550 1.6893442 1.0000000 10.0000000
RetailPrice 6281550 157.2914336 0.6300000 6257.20
Cost 6281550 86.7235972 0.4000000 1583.60

 

The log shows that the DATA step read 6,281,550 Germany rows and completed in about 15 seconds. PROC MEANS then read the same rows again to create the summary report and also completed in about 15 seconds, displaying the appropriate subtitle. So, this version works correctly, but it processes millions of observations on the compute server before creating the macro variable and producing the report.

Let’s revise the program to read a CAS table, hoping to get better performance in the DATA Step.

%let country=Germany;
 
data _null_ ;
set casuser.bigorders end=last;
where country="&country";
if ordertype='Retail Sale' then retail+1;
if last then do;
if retail>0 then do;
call symputx('subtitle',catx(" ","&country has",
put(retail,comma12.),"retail orders."));
end;
else call symputx('subtitle',"&country has no Retail Orders");
end;
run;
 
title "Order Statistics for &country";
title2 "&subtitle";
proc means data=casuser.bigorders n mean min max ;
var Quantity RetailPrice Cost ;
where Country="&country";
run;
title;

The revised program is essentially the same as the original, except that work.bigorders has been replaced with the CAS in-memory table, casuser.bigorders. The log excerpt below shows the results when the program runs.

Relevant log excerpt

DATA step
 
NOTE: The where clause is being processed by Cloud Analytic Services.
NOTE: Could not execute DATA step code in Cloud Analytic Services. Running DATA step in the SAS client.
NOTE: There were 6281550 observations read from the data set CASUSER.BIGORDERS.
WHERE country='Germany';
NOTE: DATA statement used (Total process time):
real time          1:25.21
cpu time           10.19 seconds
 
...
PROC MEANS step
NOTE: The where clause is being processed by Cloud Analytic Services.
NOTE: The CAS aggregation.aggregate action will be used to perform the initial summarization.
NOTE: PROCEDURE MEANS used (Total process time):
real time          1.07 seconds
cpu time           0.08 seconds

The log shows that the WHERE clause was executed in CAS to subset data, but the DATA step itself ran in the compute server (the SAS client) instead of CAS. This happens because CALL SYMPUTX cannot update the compute-side macro symbol table from CAS, so the step fell back to compute. All 6,281,550 Germany rows were pulled back from CAS, and the step took about 1 minute 25 seconds, much slower than the 15 seconds when reading WORK.BIGORDERS on compute. PROC MEANS, ran in CAS and finished in about 1 second, compared to 15 seconds in the original program.

Simply pointing the DATA step at the CAS table works, but it is not efficient. To get the benefit of CAS, separate the two tasks. Let CAS do the heavy data-intensive processing and let compute create the macro variable. The following solution does exactly that.

options msglevel=i;
 
%let country=Germany;
 
data casuser.nretail ;
set casuser.bigorders end=last;
where country="&country";
if ordertype='Retail Sale' then thread_retail+1;
if last then output;
keep thread_retail;
run;
 
data _null_;
set casuser.nretail end=last;
retail+thread_retail;
if last then do;
if retail>0 then do;
call symputx('subtitle',catx(" ","&country has",
put(retail,comma12.),"retail orders."));
end;
else call symputx('subtitle',"&country has no Retail Orders");
end;
run;
 
title "Order Statistics for &country";
title2 "&subtitle";
proc means data=casuser.bigorders n mean min max ;
var Quantity RetailPrice Cost ;
where Country="&country";
run;
title;

This revised program splits the work into two steps, as confirmed by the following log excerpt.

DATA step 1 (create casuser.nretail)
NOTE: The where clause is being processed by Cloud Analytic Services.
NOTE: Running DATA step in Cloud Analytic Services.
NOTE: The DATA step will run in multiple threads.
NOTE: There were 6281550 observations read from the table BIGORDERS in caslib CASUSER.
NOTE: The table nretail in caslib CASUSER has 48 observations and 1 variables.
NOTE: DATA statement used (Total process time):
real time          0.49 seconds
cpu time           0.06 seconds
 
...
 
DATA _NULL_ step (create subtitle)
NOTE: Could not execute DATA step code in Cloud Analytic Services. Running DATA step in the SAS client.
NOTE: There were 48 observations read from the data set CASUSER.NRETAIL.
NOTE: DATA statement used (Total process time):
real time          0.04 seconds
cpu time           0.02 seconds
 
...
 
PROC MEANS step
NOTE: The where clause is being processed by Cloud Analytic Services.
NOTE: The CAS aggregation.aggregate action will be used to perform the initial summarization.
NOTE: PROCEDURE MEANS used (Total process time):
real time          0.94 seconds
cpu time           0.08 seconds

The first DATA step runs in CAS, where the table is processed in parallel across multiple threads. Each thread counts the Retail Sale orders it sees in its share of the Germany rows, and when it reaches its last row, it outputs a single row containing that thread’s count in thread_retail. The result is the small CAS table casuser.nretail, which holds one row per thread rather than millions of rows. Because this step does not use CALL SYMPUTX, nothing needs to be written to the macro symbol table, so it can run entirely in CAS.

The second DATA _NULL_ step reads casuser.nretail. Since the table is tiny, it is quickly returned to the compute server, where the step adds up the thread counts in retail and uses CALL SYMPUTX to create the subtitle macro variable. The PROC MEANS step then runs in CAS and uses &subtitle in title2, just as before.

The key idea is the same as in Example 1: let CAS do the heavy processing when reading and summarizing large data. Use CAS to create a small result set that can then be transferred to compute to create the macro variable.

Macro programming remains a valuable part of SAS Viya programming. Most macro code continues to work because macro processing occurs on the compute server before the generated SAS statements execute in either the compute server or CAS. The adjustment comes when CAS-processed data needs to create macro variables. In those situations, separate the distributed data processing from the macro variable assignment: let CAS summarize data to produce a small result, then move the result to compute to create the macro variable.

With that pattern in mind, programmers can preserve the power of data-driven macro programming while taking advantage of CAS for scalable processing.

Learn more




Source link


administrator