formula for computed column based on different table's column
You could create a user-defined function for this:
CREATE FUNCTION dbo.GetValue(@ncode INT, @recid INT)
RETURNS INT
AS
SELECT @recid * nvalue
FROM c_const
WHERE code = @ncode
and then use that to define your computed column:
ALTER TABLE dbo.YourTable
ADD NewColumnName AS dbo.GetValue(ncodeValue, recIdValue)
This seems to be more of a job for views (indexed views, if you need fast lookups on the computed column):
CREATE VIEW AnyView
WITH SCHEMABINDING
AS
SELECT a.rec_id, a.s_id, a.n_code, a.rec_id * c.nvalue AS foo
FROM AnyTable a
INNER JOIN C_Const c
ON c.code = a.n_code
This has a subtle difference from the subquery version in that it would return multiple records instead of producing an error if there are multiple results for the join. But that is easily resolved with a UNIQUE
constraint on c_const.code
(I suspect it's already a PRIMARY KEY
).
It's also a lot easier for someone to understand than the subquery version.
You can do it with a subquery and UDF as marc_s has shown, but that's likely to be highly inefficient compared to a simple JOIN
, since a scalar UDF will need to be computed row-by-row.