我正在尝试根据下面的Scalar函数编写一个存储过程,以显示每年和每个产品有多少客户?如果产品没有客户 然后它应该在结果为零的客户数量,所以它应该显示所有的产品。然后我想将它插入临时表。这是我到目前为止所尝试的但是对于SP中的一些要点,我不知道我要做什么才能得到我的结果。我想它陷入了一个循环:( 有什么想法??
SCALAR:
CREATE FUNCTION NumOfCustomers
(
@year INT,
@productId INT,
@typeOfCustomer NVARCHAR
)
RETURNS TABLE AS
RETURN
(
SELECT COUNT(DISTINCT Sales.Customer.CustomerID) AS number
FROM Sales.SalesOrderDetail SOD
INNER JOIN Sales.SalesOrderHeader SOH ON SOD.SalesOrderID = SOH.SalesOrderID
INNER JOIN Sales.Customer ON Customer.CustomerID = SOH.CustomerID
WHERE
SOD.ProductID = @productID
AND YEAR(SOH.OrderDate) = @year
AND Sales.Customer.CustomerType = @typeOfCustomer
)
GO
存储过程:
CREATE PROCEDURE MYsp AS
BEGIN
DECLARE @year INT, @count INT
DECLARE yearCursor CURSOR FOR
SELECT DISTINCT YEAR(SOH.OrderDate) FROM Sales.SalesOrderHeader SOH
--ORDER BY YEAR DESC
OPEN yearCursor
FETCH NEXT FROM yearCursor INTO @year
--** Starting the loop in curser and filling the data
SET @count = 1
WHILE(@@FETCH_STATUS = 0)
BEGIN
DECLARE @prodID INT
DECLARE @NumOfCustomers INT
DECLARE prodCursor CURSOR FOR
SELECT P.ProductID FROM Production.Product P
OPEN prodCursor
FETCH NEXT FROM prodCursor INTO @prodID
SET @count = 1
WHILE(@@FETCH_STATUS = 0)
BEGIN
SELECT @NumOfCustomers = NUM.number FROM NumOfCustomers(@year, @prodID, 's') NUM
INSERT #temp (Year,ProductID,NumOfCustomers) VALUES (@year,@prodID,@NumOfCustomers)
SET @count = @count+1
FETCH NEXT FROM prodCursor INTO @prodID
END
CLOSE prodCursor
DEALLOCATE prodCursor
FETCH NEXT FROM yearCursor INTO @year
END
CLOSE yearCursor
DEALLOCATE yearCursor
END
GO
然后我想执行它并从临时表中获取数据:
EXEC MYsp
SELECT * FROM #temp
答案 0 :(得分:0)
在程序中使用select语句:
CREATE PROCEDURE MYsp AS
BEGIN
DECLARE @year INT, @count INT
DECLARE yearCursor CURSOR FOR
SELECT DISTINCT YEAR(SOH.OrderDate) FROM Sales.SalesOrderHeader SOH
--ORDER BY YEAR DESC
OPEN yearCursor
FETCH NEXT FROM yearCursor INTO @year
--** Starting the loop in curser and filling the data
SET @count = 1
WHILE(@@FETCH_STATUS = 0)
BEGIN
DECLARE @prodID INT
DECLARE @NumOfCustomers INT
DECLARE prodCursor CURSOR FOR
SELECT P.ProductID FROM Production.Product P
OPEN prodCursor
FETCH NEXT FROM prodCursor INTO @prodID
SET @count = 1
WHILE(@@FETCH_STATUS = 0)
BEGIN
SELECT @NumOfCustomers = NUM.number FROM NumOfCustomers(@year, @prodID, 's') NUM
INSERT #temp (Year,ProductID,NumOfCustomers) VALUES (@year,@prodID,@NumOfCustomers)
SET @count = @count+1
FETCH NEXT FROM prodCursor INTO @prodID
END
CLOSE prodCursor
DEALLOCATE prodCursor
FETCH NEXT FROM yearCursor INTO @year
END
CLOSE yearCursor
DEALLOCATE yearCursor
Select *
from #temp
END
GO
现在执行程序:
EXEC MYsp