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.
Die auf WeAreCAS.eu bereitgestellten Codes und Beispiele dienen Lehrzwecken. Es ist zwingend erforderlich, sie nicht blind in Ihre Produktionsumgebungen zu kopieren. Der beste Ansatz besteht darin, die Logik zu verstehen, bevor sie angewendet wird. Wir empfehlen dringend, diese Skripte in einer Testumgebung (Sandbox/Dev) zu testen. WeAreCAS übernimmt keine Verantwortung für mögliche Auswirkungen oder Datenverluste auf Ihren Systemen.
SAS und alle anderen Produkt- oder Dienstleistungsnamen von SAS Institute Inc. sind eingetragene Marken oder Marken von SAS Institute Inc. in den USA und anderen Ländern. ® zeigt die Registrierung in den USA an. WeAreCAS ist eine unabhängige Community-Site und nicht mit SAS Institute Inc. verbunden.
Diese Website verwendet technische und analytische Cookies, um Ihre Erfahrung zu verbessern.
Mehr erfahren.