Create Computed Column using data from another table Create Computed Column using data from another table sql sql

Create Computed Column using data from another table


You can create a user-defined function for that:

CREATE FUNCTION dbo.CountUses(@pictureId INT)RETURNS INTAS  BEGIN      RETURN        (SELECT Count(id)         FROM   PictureUse         WHERE  PictureId = @PictureId)  END 

The computed column can then be added like this:

ALTER TABLE dbo.PictureADD NofUses AS dbo.CountUses(Id)

However, I would rather make a view for this:

CREATE VIEW PictureViewAS  SELECT Picture.Id,         PictureName,         Picture.CreateDate,         Count(PictureUse.Id) NofUses  FROM   Picture         JOIN PictureUse           ON Picture.Id = PictureUse.PictureId  GROUP  BY Picture.Id,            PictureName,            Picture.CreateDate 


A computed column may only reference other columns in the same table. You could (as per jeroenh's answer) use a UDF, but the column won't be stored or be indexable and so it has to be recomputed every time the row is accessed.

You could create an indexed view that contains this information (if, as I suspect, it's just the count of rows from PictureUse):

CREATE VIEW dbo.PictureStatsWITH SCHEMABINDINGAS    SELECT PictureID,COUNT_BIG(*) as Cnt from dbo.PictureUseGOCREATE UNIQUE CLUSTERED INDEX IC_PictureStats on dbo.PictureStats (PictureID)

Behind the scenes, SQL Server will effectively create a table that contains the results of this view, and every insert, update or delete to PictureUse will maintain this results table automatically for you.


you dont have to add the computed column to your table, because, after its updated,if the original table data got changed, then data become inconsistent , you can always use this select statement to get the column count, or create it as a view

select p.id,count(*) as count from Picture Pjoin PictureUse  Uon p.id=u.Pictureid group by p.id