I have a stored procedure that calculates a special value for a given record based on the information contained within that record and some information from other tables. I’d like to write a query that returns a result table containing each record’s regular information, with the addition of each record’s calculated value in a new column. For example, I want something like this:
SELECT
[id] as Name,
[shape] as Shape,
[color] as Color,
EXEC FindCode
@id = [id]
@shape = [shape]
@color = [color]
as Code
FROM Shapes
With the equivalent of the above ‘pseudo’ code, I’d expect to get back a result set like this:
Name | Shape | Color | Code
-----+---------+-------+-----
AB | Circle | Blue | 4276
BC | Square | Red | 9825
CD | Rect | Gray | 3723
Where the Name, Shape, and Color, were already contained in the table as id, shape, and color, but the ‘Code’ was calculated using the stored procedure. What’s the best way to go about doing this in SQL Server 2008 R2?
Here are a few examples of what your query might look like using some of the suggestions in this thread.
1.
CROSS APPLYing a scalar-valued user-defined function:2. Changing your table definition to have a computed column:
3.
JOINing a table-valued user-defined function:Or 4. you could just pre-fill a different table will all of the possible color codes (if feasible).
The use of the scalar-value functions as-is in examples 1 and 2 will perform the worst, especially if it has to go after other tables, because it will execute once per row.
You can improve the performance of the computed column example by tacking on the
PERSISTEDkeyword after the column definition. This is probably how I would do it. The persisted values will be calculated once upon insert, auto-updated when a row updates, but pulled from its persisted location for a select statement.