T-SQL Pseudo-Constants


Stardate: 11047.9

How many times have you come across unfriendly T-SQL such as “IF( @statusID = 1 )” wishing instead for a more meaningful encounter such as “IF( @statusID = ActiveCustomer)”?  And if you think that is bad, try searching for all logic pertaining to active customers!  Right from CS-101, littering code with non-obvious literal constant values is strongly discouraged which is why it is really surprising that even after the release of SQL Server 2008, there is no native support for constants in T-SQL.  While we are on the subject of missing language constructs, another addition that I would really like to see in T-SQL is support for an Oracle-like “CREATE OR REPLACE” to obviate awkward “IF EXISTS…DROP…CREATE” sequences not to mention the associated chain of security processes to reapply access control.

In fairness, a CLR-based mechanism was introduced (which I will cover in a later post) to support constants in T-SQL with SQL Server 2005.  However, that requires deploying .NET assemblies making the implementation disjointed at best.  In any case, for all T-SQL developers out there, here is a work-around for implementing constants entirely in T-SQL!

First, because support for a “CREATE OR REPLACE” syntax is missing, create a helper procedure as follows (this is not entirely necessary, merely for convenience):

PROCEDURE ei_const

Next, create pseudo-constants to your heart’s content  as follows:

Defining Constants

And there you have it!  Never again be faced with the frustration of coming face-to-face with: “IF( @statusID = 1 )”

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s