The first reflex of many programmers is to try to use macro-variable features at run time via CALL SYMPUT and SYMGET.
The code often looks like this:
DATA target_ds;
SET source_ds;
/* Tentative d'assigner le nom de la variable à une macro */
CALL SYMPUT('field_val', req_stat);
/* Tentative de récupérer la valeur */
field_stat = SYMGET('field_val');
RUN;
1
DATA target_ds;
2
SET source_ds;
3
/* Tentative d'assigner le nom de la variable à une macro */
4
CALL SYMPUT('field_val', req_stat);
5
/* Tentative de récupérer la valeur */
6
field_stat = SYMGET('field_val');
7
RUN;
Why doesn't this work? The result of this code will not be the numeric value (e.g., 120), but the character string itself (e.g., "FIELD_AVG"). The SYMGET function retrieves the content of the macro-variable as is (text) and does not interpret it as a reference to a dataset variable. Moreover, managing macro-variables during the execution of a DATA step is complex because they do not update line by line as one might hope for this type of operation.
The Recommended Solution
To solve this problem of "resolving a character string into a variable name", you must abandon the idea of dynamic resolution by macro during the DATA step.
Two main approaches exist:
1. For a small number of variables: The explicit condition
If you only have a few possible columns (as in our example), the simplest and most efficient method remains the use of conditional blocks (IF/THEN/ELSE or SELECT).
DATA target_ds;
SET source_ds;
SELECT (req_stat);
WHEN ('FIELD_AVG') field_stat = field_avg;
WHEN ('FIELD_SUM') field_stat = field_sum;
OTHERWISE field_stat = .;
END;
RUN;
You can use the table's metadata to dynamically build a SELECT statement or a series of IFs via a preprocessing macro. This makes the code generic and adaptable regardless of the table structure.
The codes and examples provided on WeAreCAS.eu are for educational purposes. It is imperative not to blindly copy-paste them into your production environments. The best approach is to understand the logic before applying it. We strongly recommend testing these scripts in a test environment (Sandbox/Dev). WeAreCAS accepts no responsibility for any impact or data loss on your systems.
SAS and all other SAS Institute Inc. product or service names are registered trademarks or trademarks of SAS Institute Inc. in the USA and other countries. ® indicates USA registration. WeAreCAS is an independent community site and is not affiliated with SAS Institute Inc.
This site uses technical and analytical cookies to improve your experience.
Read more.