如何将整个查询放在存储过程中?

时间:2015-04-16 16:25:10

标签: sql sql-server tsql sql-server-2005

SELECT
    AvHours.LineNumber,
    (SProd.PoundsMade / (AvHours.AvailableHRS - SUM (ProdDtime.DownTimeHRS))) AS Throughput,
    SUM (ProdDtime.DownTimeHRS) AS [Lost Time], 
    (SUM(cast(ProdDtime.DownTimeHRS AS decimal(10,1))) * 100) / (cast(AvHours.AvailableHRS AS decimal(10,1))) AS [%DownTime],
    SUM(SProd.PoundsMade) AS [Pounds Made],
   (SProd.PoundsMade / (AvHours.AvailableHRS - SUM (ProdDtime.DownTimeHRS))) *  SUM (ProdDtime.DownTimeHRS) AS [Pounds Lost]
FROM 
    rpt_Line_Shift_AvailableHrs AvHours
INNER JOIN  
    rpt_Line_Shift_Prod SProd ON AvHours.LineNumber = SProd.LineNumber 
                              AND AvHours.Shiftnumber = SProd.Shiftnumber
INNER JOIN
    rpt_Line_Shift_ProdDownTime ProdDtime ON (AvHours.LineNumber = ProdDtime.LineNumber AND 
                                           AvHours.Shiftnumber = ProdDtime.Shiftnumber)
GROUP BY 
     AvHours.LineNumber, SProd.PoundsMade, AvHours.AvailableHRS
ORDER BY 
     AvHours.LineNumber

1 个答案:

答案 0 :(得分:0)

您可以使用CREATE PROCEDURE语句创建新的存储过程:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE YourProcedureNameHere
AS
BEGIN
    SET NOCOUNT ON;

    -- Insert statements for procedure here

END
GO

在您的具体情况下,该陈述应如下所示:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE YourProcedureNameHere
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        AvHours.LineNumber,
        (SProd.PoundsMade / (AvHours.AvailableHRS - SUM (ProdDtime.DownTimeHRS))) AS Throughput,
        SUM (ProdDtime.DownTimeHRS) AS [Lost Time], 
        (SUM(cast(ProdDtime.DownTimeHRS AS decimal(10,1))) * 100) / (cast(AvHours.AvailableHRS AS decimal(10,1))) AS [%DownTime],
        SUM(SProd.PoundsMade) AS [Pounds Made],
       (SProd.PoundsMade / (AvHours.AvailableHRS - SUM (ProdDtime.DownTimeHRS))) *  SUM (ProdDtime.DownTimeHRS) AS [Pounds Lost]
    FROM 
        rpt_Line_Shift_AvailableHrs AvHours
    INNER JOIN  
        rpt_Line_Shift_Prod SProd ON AvHours.LineNumber = SProd.LineNumber 
                                  AND AvHours.Shiftnumber = SProd.Shiftnumber
    INNER JOIN
        rpt_Line_Shift_ProdDownTime ProdDtime ON (AvHours.LineNumber = ProdDtime.LineNumber AND 
                                               AvHours.Shiftnumber = ProdDtime.Shiftnumber)
    GROUP BY 
         AvHours.LineNumber, SProd.PoundsMade, AvHours.AvailableHRS
    ORDER BY 
         AvHours.LineNumber

END
GO

请注意,Microsoft SQL Management Studio可以自动为您的存储过程创建存根(几乎是此答案中的第一个代码段),右键单击项目"存储过程"在[您的数据库] /可编程性下,选择"新存储过程......"从上下文菜单中:

enter image description here