Published on :
Macro SASHELP

Macro Variable Existence Check with Scope

This code is also available in: Deutsch Español Français
This macro, named `mvartest`, extends the functionality of SAS©'s `%SYMEXIST()` macro function. It allows determining if a macro variable exists, not only by its name but also within a specific macro scope. The input parameters are `mvar` (the name of the macro variable to check) and `scope` (the optional macro scope in which to perform the search). The macro dynamically constructs a WHERE clause to query the `sashelp.vmacro` system view. It returns `1` if the macro variable is found within the specified scope (or globally if no scope is provided), and `0` otherwise.
Data Analysis

Type : SASHELP


The macro exclusively queries the `sashelp.vmacro` system view, which contains metadata on all existing macro variables in the SAS session. No other external data sources are used or created.

1 Code Block
Macro Logic (WHERE clause construction)
Explanation :
This first block initializes three local macro variables: `dsid` (for the dataset identifier), `rc` (for the return code), and `where` (for the filtering clause). It then constructs the `WHERE` clause that will be used to query the `sashelp.vmacro` view. If the `scope` parameter is provided, the search is limited to the specified scope, converted to uppercase. Otherwise, the search excludes the current macro's scope (`&sysmacroname`). Finally, the `WHERE` clause is completed to include the name of the macro variable to search for (`&mvar`), also converted to uppercase.
Copied!
1%local dsid rc where;
2 
3%IF %LENGTH(&scope) %THEN %let where=scope=%upcase("&scope");
4%ELSE %let where=scope ^= "&sysmacroname" ;
5%let where=name=%upcase("&mvar") and &where;
2 Code Block
Macro Data Access Functionality
Explanation :
This second block executes the verification logic. It uses the `%sysfunc(open())` function to open the `sashelp.vmacro` system view, applying the previously defined `WHERE` clause. If the dataset is successfully opened (i.e., `&dsid` is not null), the macro attempts to retrieve a record using `%sysfunc(fetch(&dsid))`. If a record is found (indicated by a return code other than -1), it means the macro variable exists in the searched scope. The dataset is then closed with `%sysfunc(close(&dsid))`. The macro returns `1` if the macro variable is found and `0` otherwise.
Copied!
1%let dsid = %sysfunc(open(sashelp.vmacro(where=(&where))));
2%IF (&dsid) %THEN %DO;
3 %eval(%sysfunc(fetch(&dsid)) ^= -1)
4 %let rc = %sysfunc(close(&dsid));
5%END;
6%ELSE 0;
This material is provided "as is" by We Are Cas. There are no warranties, expressed or implied, as to merchantability or fitness for a particular purpose regarding the materials or code contained herein. We Are Cas is not responsible for errors in this material as it now exists or will exist, nor does We Are Cas provide technical support for it.