如何使用存储过程添加百分比列

时间:2014-04-21 07:03:50

标签: sql-server-2008 stored-procedures

我正在尝试使用存储过程添加百分比列。我得到了学生总分的专栏,但没有计算出百分比。我在一个名为tbl_Marks的表中有不同的主题标记,然后我编写了一个用于添加总列的存储过程。

这是我的存储过程代码:

ALTER PROCEDURE [dbo].[Sp_TotalMarks]
AS
BEGIN
   DECLARE @t int
   DECLARE @p int

   SET @t = 300
   SET @p = 100

   SELECT 
      Student_Id, Stu_Name, Maths, English, Hindi,
      (Maths + English + Hindi) AS 'Total',
      ((Maths + English + Hindi )/@t)* @p AS 'Percentage'
   FROM 
      tbl_Marks
END

1 个答案:

答案 0 :(得分:1)

试试这个:

ALTER PROCEDURE [dbo].[Sp_TotalMarks]

AS
BEGIN
DECLARE @t numeric(8,2)
DECLARE @p int

SET @t = 300
SET @p = 100
SELECT 
Student_Id,
Stu_Name,
Maths,
English,
Hindi,
(Maths + English + Hindi) AS 'Total',
CAST(CAST((Maths + English + Hindi) AS NUMERIC(8,2)) / @t * 100 AS NUMERIC(8,2)) AS 'Percentage'

FROM tbl_Marks
END

如果要保留百分比结果,则在表中添加新列,将计算,添加一个公式,检查以保持结果以获得更好的性能。