Create Computed Column using data from another table

后端 未结 5 727
忘掉有多难
忘掉有多难 2020-12-01 16:52

I have a SQL Server 2008 R2 database. This database has two tables called Pictures and PictureUse.

Picture table has the following columns:

Id (int)          


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 17:29

    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.PictureStats
    WITH SCHEMABINDING
    AS
        SELECT PictureID,COUNT_BIG(*) as Cnt from dbo.PictureUse
    GO
    CREATE 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.

提交回复
热议问题