Yes, you can do this - you need a function to count the players for the team and use it in the calculated 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 choose, this function is called every time, for each selected command. The value is not stored in the Team table - it is calculated on the fly every time you select Team from the table.
Since this value is not saved, the question actually arises: does it need a calculated column in the table, or can you just use the stored function to calculate the number of players, if necessary?
source share