SAS Custom Tasks: Wrap your variable names appropriately

0

The following is an excerpt from my forthcoming book: Creating Custom Tasks for SAS Enterprise Guide using Microsoft .NET.

If your custom task generates a SAS program, the chances are pretty high that your program will reference one or more variables within a SAS data set. Despite our best efforts, not all variable names follow the old-style SAS naming rules, and SAS has an option for that.

The option is called VALIDVARNAME=ANY. When enabled, SAS allows you to use variable names that contain spaces or special characters in their names. However, SAS requires that you express these variable names by using special "name literal" syntax, which includes quoting the name and adding n as a name indicator.

For example, you can create a variable named "My Crazy Variable Name!" with SAS code like this:

length "My Crazy Variable Name!"n 8;

While most SAS programmers don't willingly use variable names like this, SAS Enterprise Guide makes it easy for you to create such names unwittingly. For example, when you import data from a Microsoft Excel spreadsheet, the column headings might not comply with SAS naming rules. Since these column headings automatically become the variable names in your data set, SAS Enterprise Guide generates the proper literal syntax automatically.

As a task developer, you have to make sure that you also handle such variable names, as they might be found in the task's input data. The SAS Task Toolkit library provides a helper function that automatically applies the name literal syntax: SAS.Tasks.Toolkit.Helpers.UtilityFunctions.SASValidLiteral(). Here's an example of how to use it in C# (where VariableTotal and VariableMeasure are local string fields that contain names of SAS variables):

using SAS.Tasks.Toolkit.Helpers; 
/* ... */
program.AppendFormat(" COLUMNS {0} {1}; \n",
    UtilityFunctions.SASValidLiteral(VariableTotal), 
    UtilityFunctions.SASValidLiteral(VariableMeasure));

The SASValidLiteral function simply returns the name of the variable as-is, unless the variable name doesn't comply with SAS naming rules. In that case, it quotes the name and adds the n indicator. It also handles other evil little nuances, such as the case where the variable name contains a quote, in which case it uses the proper approach to escape that character and thus keep the SAS language parser happy.

Share

About Author

Chris Hemedinger

Director, SAS User Engagement

+Chris Hemedinger is the Director of SAS User Engagement, which includes our SAS Communities and SAS User Groups. Since 1993, Chris has worked for SAS as an author, a software developer, an R&D manager and a consultant. Inexplicably, Chris is still coasting on the limited fame he earned as an author of SAS For Dummies

Comments are closed.

Back to Top