Question

I can't find any answer for my problem on the web.

When exactly are computed columns computed? (not persisted ones)

When I select TOP 100 from thousands of records, are they calculated for only those selected rows? What if I add a WHERE clause for the computed column? Does this change?

The main problem is that I have a one to many relationship, but I want to have information on parent side about... let's say MAX(somecolumn) of child table. I'm using Entity Framework. I decided to make a computed column. Is this a good idea? Are there any others? Any help appreciated. Tnx

EDIT: My column is defined like this:

[ComputedNextClassDate] as [dbo].[ComputeNextClassDate]([Id]),

And my function:

CREATE FUNCTION [dbo].[ComputeNextClassDate](@id INT)
RETURNS DATETIME
AS
BEGIN
DECLARE @nextDate DATETIME;
DECLARE @now DATETIME = GETUTCDATE();
SELECT  @nextDate = MIN(Start) FROM [dbo].[Events] WHERE [Start] > @now AND [GroupClassId] = @id
RETURN @nextDate;
END;
Était-ce utile?

La solution

For the calculated columns with no persistance, the calculation result is never stored. On query execution, SQL Server engine search an execution plan. If your query has been well written, the value will be calculated only once even if it is used at many places into your query.

My opinion, I never use calculated columns with no persistence. The calculation must be done at the insertion or when reading. SQL Server, and others, are ineficient for calculation usually. Call the CLR is catastrophic in terms of performance. Avoid it.

Prefer multiples tables with joins like

SELECT p.product_name
    , SUM(ISNULL(sales,0)) 
FROM product p
    LEFT OUTER JOIN sales s ON p.product_id = s.product_id
GROUP BY p.product_name
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top