formula for computed column based on different table's column

前端 未结 2 976
囚心锁ツ
囚心锁ツ 2020-11-28 08:06

Consider this table: c_const

 code  |  nvalue
 --------------
 1     |  10000
 2     |  20000  

and another table t_anyt

相关标签:
2条回答
  • 2020-11-28 08:26

    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.

    0 讨论(0)
  • 2020-11-28 08:27

    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)
    
    0 讨论(0)
提交回复
热议问题