WileCau
WileCau

Reputation: 2197

What is the best way to define a named constant in SQL?

If a "constant" value is required in multiple stored procedures and functions in a database, is there a standard way to define it in one place so it is available everywhere?

For example, suppose I use xp_logevent in CATCH block to write something to the event log when RAISERROR happens, but I want to group the severity into informational, warning, and error based on the RAISERROR severity.

I could set a constant EventSeverity such that:

The cut-off between warning and error severity is unlikely to change, but if it ever does I want to change it in one place only.

I thought of these possibilities:

Is there a best practice way to do this?

Upvotes: 6

Views: 17253

Answers (1)

Lynx Kepler
Lynx Kepler

Reputation: 662

All else being equal, I would settle for the hard-coded FUNCTION, for performance. For security, this function should be put in a distinct SCHEMA, like MyDatabase.CONF.SettingsFunc instead of the usual DBO; with permissions set to this schema so only the administrators would have permission to change data.

If you need to centralize various configuration settings for many different uses, then the last approach (FUNCTION+TABLE) would have a larger appeal, providing you create an index for each and every use case. Likewise, this "settings" table should be in a restricted schema, unlike the function, which could remain in the default schema for ease of coding.

But, if it is mandatory that the default schema is to be used, it becomes interesting to configure an "INSTEAD OF UPDATE" trigger in this "settings" table, so the user wouldn't change data easily; don't forget that this latter approach can not be called "security" as the user could still change (or drop!) the trigger.

Upvotes: 3

Related Questions