When writing TSQL stored procedures I find myself wanting to centralize / normalize some parts of the code. For example, if I have a query like this:
SELECT * FROM SomeTable WHERE SomeColumn IN (2, 4, 8)
For cases like this I would like to put (2,4,8) in some place outside of the procedure that I could reuse in some other query later — to avoid repetition. Is there a built-in way to do this? What would really neat is if I could break apart entire pieces of SQL code, like parts of the WHERE clause, and reuse those in other queries, but I doubt this is possible.
Thanks.
I’ve often wanted a similar thing but that specifically does not exist. Here are a couple of things you can do.
Option 1
What we have done is used User Defined Functions (UDF) to gather what you might call global variables.
You’re able to call a UDF inline within your query which makes it really useful.
Suppose you wanted to specify a server name which you’d use across multiple stored procedures. Duplicating that value wouldn’t be optimally maintainable. Instead you might do something like:
Option 2
This one is more obvious but worth pointing out. Keep your values in a lookup table and reference it by an ID. The ID wouldn’t change but the value it refers to might. Using the sample example as above but for this option:
This is a typical approach to database normalization but people don’t necessarily think about this for purposes of keeping DB-logic data centralized.
I hope that helps! Ian