Published on :
Macro EXTERNE

Utility Macro for Truncating a SAS Table

This code is also available in: Deutsch Español Français
This macro, named DI_UTIL_TRUNCATE_TABLE, allows emptying a table of all its data without deleting it. It uses a two-step method: first, it exports the table's structure (but no data thanks to the OBS=0 option) into a temporary transport file via PROC CPORT. Then, it re-imports this structure from the temporary file with PROC CIMPORT, which effectively overwrites the existing table with an empty table. Indexes and constraints are preserved. The macro also saves and restores the system options OBS and NOTES to avoid affecting the user's environment.
Data Analysis

Type : EXTERNE


The macro operates on an existing SAS table whose name is provided as a parameter. No data is created or read from SASHELP.

1 Code Block
MACRO
Explanation :
This block defines the `DI_UTIL_TRUNCATE_TABLE` macro. It takes a table name as a parameter. Execution begins by saving the global `obs` and `notes` options. Then, it sets `obs=0` to read no observations and uses `PROC CPORT` to export only the structure of the input table to a temporary file. If this step succeeds (`syserr=0`), `PROC CIMPORT` is called to re-import the structure from the temporary file into the same table, which effectively empties it. Finally, the initial `obs` and `notes` options are restored. An `EXIT` label is used to ensure that options are restored even in case of an error.
Copied!
1%macro DI_UTIL_TRUNCATE_TABLE( TABLE ) ;
2 
3 *------save caller environment------;
4 %local callerobs;
5 %let callerobs = %sysfunc(getoption(obs));
6 %local callernotes;
7 %let callernotes = %sysfunc(getoption(notes));
8 
9 
10 *------cport zero obs of the table silently to capture table definition------;
11 options obs=0 nonotes;
12 filename tranfile temp;
13 PROC CPORT file=tranfile DATA=&TABLE; RUN;
14 %IF &syserr ne 0 %THEN %goto EXIT;
15 
16 
17 *------cimport the empty table definition------;
18 PROC CIMPORT INFILE=tranfile DATA=&TABLE extendsn=no; RUN;
19 %IF &syserr ne 0 %THEN %goto EXIT;
20 options obs=&callerobs &callernotes;
21 %put NOTE: %qupcase(&TABLE) has been truncated.;
22 
23 
24%EXIT:
25 options obs=&callerobs &callernotes;
26 
27%mend DI_UTIL_TRUNCATE_TABLE;
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.
Copyright Info : Copyright (C) 2016 SAS Institute, Inc. All rights reserved.