Monday 14 January 2013

NOTE: The OPEN Function (error trapping)

In my previous two posts on this topic (listed at the bottom of this post), I've described how to use the OPEN function (and its counterparts) to read data sets from macro code, and to read data sets within a DATA step without using the SET/UPDATE/MODIFY statement. In this final post, I'll tidy-up a few loose-ends, including error-trapping.

Firstly, I haven't mentioned the FETCHOBS function. Whilst FETCH simply fetches the next row, FETCHOBS fetches the specified row number, e.g. RC=FETCHOBS(DSID,7) to fetch the seventh row.

Next, I'll mention the SYSMSG function which returns the warning/error message from the most recent data set function. There are a lot of reasons why your data set functions may not give you the results that you expect, so it's worth being aware of SYSMSG. While I'm developing my code, I use a defensive technique and place a PUT statement alongside my data set functions to show me all of the return codes as I progress with my code. Here's a log with a simple example:

17 data _null_;
18   dsid = open('SASHELP.CARS(where=(left(model) eq "XJR 4dr")))');
19     sm=sysmsg(); put DSID= SM=;

20   call set(dsid);
21   rc=fetch(dsid); sm=sysmsg(); put RC= SM=;

22   rc = close(dsid); sm=sysmsg(); put RC= SM=;
23 run;

dsid=1 sm=
rc=10005 sm=ERROR: ERROR: DATA step variable Make not defined..
rc=0 sm=

See how SYSMSG tells us that we haven't pre-defined the MAKE variable (because we've used CALL SET but haven't used a LENGTH statement nor a SET statement with a never-true IF statement).

I hope you've found interest in this mini-series on the OPEN function and its counterparts. Those who have knowledge of SCL programming with SAS/AF will already be familiar with these functions (and many more that haven't been supporetd in teh DATA step). They're not of use every day, but they're damn valuable when the right situation arises!


1. NOTE: The OPEN Function (getting data set information in macros)
2. NOTE: The OPEN Function (reading data sets in macros)
3. NOTE: The OPEN Function (error trapping)