define a computed column reference another table

后端 未结 2 817
既然无缘
既然无缘 2020-12-16 05:44

I have two database tables, Team (ID, NAME, CITY, BOSS, TOTALPLAYER) and Player (ID, NAME, TEAMID, AGE), the rel

相关标签:
2条回答
  • 2020-12-16 06:13

    You don't have to store the total in the table -- it can be computed when you do a query, something like:

    SELECT teams.*, COUNT(players.id) AS num_players
    FROM teams LEFT JOIN  players ON teams.id = players.team_id
    GROUP BY teams.id;
    

    This will create an additional column "num_players" in the query, which will be a count of the number of players on each team, if any.

    0 讨论(0)
  • 2020-12-16 06:21

    Yes, you can do that - you need a function to count the players for the team, and use that in the computed column:

    CREATE FUNCTION dbo.CountPlayers (@TeamID INT)
    RETURNS INT 
    AS BEGIN
        DECLARE @PlayerCount INT
    
        SELECT @PlayerCount = COUNT(*) FROM dbo.Player WHERE TeamID = @TeamID
    
        RETURN @PlayerCount
    END
    

    and then define your computed column:

    ALTER TABLE dbo.Team
    ADD TotalPlayers AS dbo.CountPlayers(ID) 
    

    Now if you select, that function is being called every time, for each team being selected. The value is not persisted in the Team table - it's calculated on the fly each time you select from the Team table.

    Since it's value isn't persisted, the question really is: does it need to be a computed column on the table, or could you just use the stored function to compute the number of players, if needed?

    0 讨论(0)
提交回复
热议问题