多次执行函数或创建存储过程

时间:2016-09-26 22:04:21

标签: sql-server stored-procedures user-defined-functions

假设我有这样的功能

SELECT 
    ROW_NUMBER() OVER (ORDER BY T1.FinalScore desc) as Position, 
    T1.Employee, T1.FinalScore
FROM 
    (SELECT 
         Position, Employee, AVG(Score) as FinalScore
     FROM 
         dbo.Answers
     WHERE 
         DATEPART(year, EvaluationDate) = @Year
     GROUP BY   
         Employee) as T1

这将返回如下表格:

|--------|----------|-------|
|Position| Employee | FScore|
|========|==========|=======|
|   1    |   John   |  5.6  |
|   2    |   Tom    |  4.8  |
|   3    |   Paul   |  3.6  |
|   4    |   Mark   |  2.0  |

现在我需要创建一个包含上一张表的趋势图,以及前几年的信息。

我的问题是,最好的做法是什么,我应该从我的asp.net页面多次调用我的函数来检索几个表,并处理我页面上的信息。

或者我应该创建一个多次执行此函数的存储过程并将数据插入临时表?像这样:

CREATE TABLE #TOP 
(
     Position int, 
     Employee nvarchar(60), 
     Score decimal(18,2)
)

DECLARE @Flag as int

SET @Flag = @Year - 3

WHILE (@Year > @Flag)
BEGIN
   INSERT INTO #TOP
       SELECT * 
       FROM dbo.MyFunction(@Year)

   SET @Year = @Year -1
END

SELECT * FROM #TOP
DROP TABLE #TOP

1 个答案:

答案 0 :(得分:0)

首先,您可以将查询简化为:

   SELECT row_number() over (order by avg(Score)) as position,
          Employee, AVG(Score) as FinalScore
   FROM dbo.Answers
   WHERE DATEPART(year, EvaluationDate) = @Year
   GROUP BY Employee;

然后,如果您想要这么多年,请使用partition by

   SELECT row_number() over (partition by year(EvaluationDate) order by avg(Score)) as position,
          Employee, AVG(Score) as FinalScore
   FROM dbo.Answers
   GROUP BY Employee, year(EvaluationDate);