显然,存储过程语法比我预期的更难理解

时间:2011-07-21 08:44:37

标签: sql-server stored-procedures

所以基本上我正在尝试将此查询复制为存储过程。

Use ThisDB   
  SELECT FirstName + ' ' + LastName as FullName ,     
         sum(UnitPrice * Quantity) as 'Total Sales',   
         YEAR(OrderDate) as SalesYear   
  From Employees e   
      Join Orders o on o.EmployeeID = e.EmployeeID    
      join [Order Details] od on od.OrderID = o.OrderID   
      Group by LastName +' ' +FirstName, YEAR(OrderDate)
      Order by 'Total Sales' desc

编辑:我注意到旧查询会失败,但不会改变太多 / edit

不幸的是,我没有找到任何好的示例来帮助我将我对查询的了解翻译成存储过程语法。这是我到目前为止所理解的:

Use ThisDB;
go
CREATE PROCEDURE empSalesByYear as @Emp OUT  
BEGIN  
     Set Emp = (SELECT Employees.FirstName, Employees.LastName ,   
            TotalSales = sum([Order Details].UnitPrice * [OrderDetails].Quantity),
        YEAR(orders.OrderDate) as SalesYear   
             From Employees e  
         Join Orders o on o.EmployeeID = e.EmployeeID
             join [Order Details] od on od.OrderID = o.OrderID
             group by FirstName , LastName
             Order by TotalSales desc)  
END  
GO

可以预见,当我输入所有这些时,SQL server会给我指责。

我的目标是一个存储过程,它接受零输入参数并输出类似第一个查询的表。

感谢。

1 个答案:

答案 0 :(得分:1)

继续我的评论,您可以这样做:

CREATE PROCEDURE proc_GetEmpSalesByYear AS

SELECT FirstName + ' ' + LastName as FullName ,
sum(UnitPrice * Quantity) as 'Total Sales',
YEAR(OrderDate) as SalesYear
From ThisDB..Employees e
Join ThisDB..Orders o on o.EmployeeID = e.EmployeeID
join ThisDB..[Order Details] od on od.OrderID = o.OrderID
Group by LastName, FirstName Order by 'Total Sales' desc

GO

..除非你想返回一个表输出参数?

(删除了USE,错过了..现在使用db..table格式)