Question

  Asked: Mar 16 2008   10:25 PM GMT
  Asked by: SQL Server Ask the Experts


Design a SQL Server trigger to calculate column averages and return them to another table


SQL Server performance, SQL Server development, Triggers

I'm quite new to SQL Server and I’m struggling to design a trigger. I need this trigger to execute daily and calculate averages of columns and return them to another table.

Subscribe to Alerts! Get questions and answers delivered to your Inbox.


E-mail me updates on this question



   SUBSCRIBE

hidden modal window

Answer Wiki (Improve, edit or add to this answer)


 RATE THIS ANSWER
0
Click to Vote:
  •   0
  •  0



What you want is actually a stored procedure not a trigger. Triggers can not be fired off on schedule, while stored procedures can. First you need to write your select statement which simply returns the data that you need to load into the destination table. The query will look something like this.

SELECT IdField, AVG(NumericField)
FROM Table
GROUP BY IdField


You then turn this into an insert statement.
INSERT INTO AnotherTable
SELECT IdField, AVG(NumericField)
FROM Table
GROUP BY IdField


You then wrap this in the stored procedure wrapper to save the procedure.

CREATE PROCEDURE MyProcedure
AS
INSERT INTO AnotherTable
SELECT IdField, AVG(NumericField)
FROM Table
GROUP BY IdField
GO


You can then setup a SQL Agent Job to run this procedure nightly.
  • AddThis Social Bookmark Button

Browse more Questions and Answers on SQL Server and Database.

Looking for relevant SQL Server Whitepapers? Visit the SearchSQLServer.com Research Library.


Discuss This Answer


You must be logged-in to discuss a question. Log-in/Register

Mrdenny  |   Mar 16 2008  11:36PM GMT

Check out my SQL Server blog “SQL Server with Mr Denny” for more SQL Server information.

Specifically you may want to check out my Back To Basics series which I’ve just started on my blog. So far I’ve only covered the SELECT statement, but the other commands will be coming shortly.