Computed column in SQL Server

NishchalG 41 Reputation points
2021-01-15T16:55:29.3+00:00

Can we populate a computed column in parent table with values calculated from records in child table ?
Reagards

SQL Server Other
{count} votes

3 answers

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2021-01-15T22:40:52.533+00:00

    Yonggang Huang's reply is technically correct, except for the last sentence - you cannot persist the column, since the if the data is updated in the child table is updated, the column in the parent table should change its value.

    However, I recommend against using a scalar function in a computed column, and even more a scalar function that accesses in another table. This comes with a big performance overhead, as the function will be called for every row. This applies also SQL 2019, since inlining of scalar functions does not happen with computed columns.

    There are two alternatives:

    1. Define a view which evades the need for the scalar function.
    2. Make the column a real column which is populated from the data in the child tables through triggers. This is a more advanced solution and you need to know what you are doing.
    1 person found this answer helpful.

  2. Guoxiong 8,206 Reputation points
    2021-01-15T21:06:21.713+00:00

    You cannot insert or update the computed column.


  3. CathyJi-MSFT 22,396 Reputation points Microsoft External Staff
    2021-01-18T08:19:38.73+00:00

    Hi @NishchalG ,

    Please check if the suggestions from below threads could help you.

    Create Computed Column using data from another table
    How to create trigger that updates field on parent with the sum from 2 children

    Best regards,
    Cathy


    If the response is helpful, please click "Accept Answer" and upvote it, thank you.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.