100分:大抛卖啦 走过路过不要错过,一个sp问题
有个SP执行要化十多分钟,代码如下:
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N '[dbo].[usp_StatisticsTotalPurchase] ') AND OBJECTPROPERTY(id, N 'IsProcedure ') = 1)
DROP PROC [dbo].[usp_StatisticsTotalPurchase]
GO
CREATE PROC [dbo].[usp_StatisticsTotalPurchase]
@Reference INT,
@BeginDate DATETIME,
@EndDate DATETIME,
@ErrorNumber INT OUTPUT,
@ErrorInfo NVARCHAR(200) OUTPUT
AS
SET NOCOUNT ON;
DECLARE @Profit MONEY
, @RefStandardCost MONEY
, @PartID NVARCHAR(60)
, @Mode NVARCHAR(10)
, @Date DATETIME
, @YearMonth NVARCHAR(6);
--得到利润率
SELECT @Profit = Profit
FROM dbo.Profit
WHERE Active = 1;
IF @Profit IS NULL
BEGIN
SELECT @ErrorNumber = 110, @ErrorInfo = N 'Profit data not set. ';
SET NOCOUNT OFF;
RETURN CAST(0 AS BIT);
END;
--确定统计的部件
DECLARE @Parts TABLE
(
PartID NVARCHAR(60) COLLATE Chinese_PRC_CI_AS NOT NULL PRIMARY KEY,
RefStdCost MONEY
);
IF LEN(CAST(@Reference AS NVARCHAR)) = 6
INSERT INTO @Parts (PartID)
SELECT DISTINCT PartID
FROM dbo.StandardCost
WHERE IsPurchased = 1
AND YEAR([Date]) * 100 + MONTH([Date]) <= @Reference;
ELSE
INSERT INTO @Parts (PartID)
SELECT DISTINCT PartID
FROM dbo.StandardCost
WHERE IsPurchased = 1
AND YEAR([Date]) <= @Reference;
DELETE @Parts
FROM @Parts p
INNER JOIN
(
SELECT PartID
FROM dbo.StandardCost
GROUP BY PartID
HAVING SUM(Price) = 0
) c
ON p.PartID = c.PartID;
DELETE @Parts
FROM @Parts p
WHERE NOT EXISTS
(
SELECT 1
FROM iERP72tech.dbo.POM pom
INNER JOIN iERP72tech.dbo.POI poi
ON poi.POI_PurchOrderID = pom.POM_PurchOrderID
INNER JOIN iERP72tech.dbo.POD pod
ON pod.POD_PurchOrderID = pom.POM_PurchOrderID
AND pod.POD_POLineNbr = poi.POI_POLineNbr
WHERE poi.POI_LineNbrTypeCode = N 'Item '
AND pod.POD_POUnitPrice > 0
AND pom.POM_PurchOrderDate > = @BeginDate
AND pom.POM_PurchOrderDate < DATEADD(DAY, 1, @EndDate)
AND poi.POI_ItemID COLLATE Chinese_PRC_CI_AS = p.PartID
);
IF NOT EXISTS (SELECT 1 FROM @Parts)
BEGIN
SELECT @ErrorNumber = 110, @ErrorInfo = N 'Standard cost in reference period not exists. ';
SET NOCOUNT &n