Get total from table Item: computed column or group by?

  • Hello,

    I need to get the Total value by SUM the records of a Table Item.

    What would be the quickest way?

    - using a computed column on master table and get value by function

    or

    - make a SUM select with group by on table Item ?

    Examples:

    -- total is a computed column get by dbo.fu_salesTotal( )

    select idSale, total from sales

    -- get total by SUM

    select S.idSale, sum(I.valueItem) as total

    from salesItems I

    inner join sales S ON S.idSale = I.idSale

    group by S.idSale

    -- Function

    create function dbo.fu_salesTotal(@idSale int) returns decimal(12,2)

    as

    begin

    declare @value decimal(12,2);

    select @value = sum(valueItem)

    from salesItems

    where idSale = @idSale

    return isnull(@value, 0);

    end;

    go

    Thank you!

    JoseACJr

  • Better would be an inline-table-valued-function.

    If you intend to stick with a scalar function, at least get rid of the variable:

    create function dbo.fu_salesTotal(@idSale int)

    returns decimal(12,2)

    as

    begin;

    return isnull((

    select sum(valueItem)

    from salesItems

    where idSale = @idSale

    ), 0);

    end;

    go

    SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.

  • Hello, thank you,

    But, is it possible to use a table value function in a computed column?

    JoseAcJR

  • No, that's true, but you could use it in a view.

    SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply