PL/SQL 填充事实的存储过程 Table

PL/SQL Stored Procedure to Populate Fact Table

我需要使用 PL/SQL 存储过程来填充这个事实 table:

CREATE TABLE SALES_FACTS
(saleDay        DATE,
vehicleCode         INT,
planID          INT,
dealerID        INT,
vehiclesSold        INT,
grossSalesAmt   NUMBER(10),
CONSTRAINT SALE_DAY_FK FOREIGN KEY (saleDay) REFERENCES TIMES(saleDay) ON DELETE CASCADE,
CONSTRAINT VEHICLE_CODE_FK FOREIGN KEY (vehicleCode) REFERENCES VEHICLES(vehicleCode) ON DELETE CASCADE,
CONSTRAINT PLAN_ID_FK FOREIGN KEY (planID) REFERENCES FINANCING_PLANS(planID) ON DELETE CASCADE,
CONSTRAINT DEALER_FK FOREIGN KEY (dealerID) REFERENCES DEALERSHIPS(dealerID) ON DELETE CASCADE,
CONSTRAINT SALES_FACTS_PK PRIMARY KEY (saleDay, vehicleCode, planID, dealerID));

我被要求通过使用四个嵌套游标循环来获取维度 table 主键的每个可能组合,以及每个组合的售出车辆总数和总销售额。

此外,如果 vehiclesSoldgrossSalesAmount 的值为零,则 不应 行插入 SALES_FACTS table.

只应插入销售了一些车辆的四个外键列组合的行。

我创建了以下代码,我希望它能完成此任务:

CURSOR factData IS

SELECT vehicleVin,saleDate,sf.planID,sp.dealerID
    COUNT (*) AS vehiclesSold
    SUM (s.grossSalePrice) AS grossSalesAmount
FROM SALES s, SALES_FINANCINGS sf, SALESPERSONS sp
WHERE s.saleID = sf.saleID
AND s.salespersonID = sp.salespersonID
GROUP BY vehicleVIN, saleDate, sf.planID, sp.dealerID
HAVING COUNT(*) > 0;
BEGIN
FOR record IN factData
LOOP
    INSERT INTO SALES_FACTS (saleDay,vehicleCode,planID,dealerID,vehiclesSold, grossSalesAmount
    VALUES (record.saleDate,record.vehicleVin,record.planID,record.dealerID,record.vehiclesSold,record.grossSalesAmount);
END LOOP;
END;
/

但是代码执行得很好,但是当我 运行 a

时我没有得到任何结果
SELECT COUNT(*) FROM SALES_FACTS;

我在这里 SQL Fiddle link 创建了一个 http://sqlfiddle.com/#!4/9708d6/1 因为 table 和 table 人口的代码太在这个问题上 post。请记住,我只 INSERT 为每个 table 编辑了大约 2-3 行数据以保持代码稍微短一些,但是已插入的数据应该足以让它工作。

请让我知道哪里出错了,最好的解决方法是什么!提前致谢!

这终于成功了。感谢所有评论者的帮助。

DECLARE
CURSOR sales_data
IS
 SELECT vehicleVIN, saleDate, SF.planID, SP.dealerID, 
 COUNT(*) AS vehiclesSold, SUM(S.grossSalePrice) AS grossSalesAmt
 FROM SALES S, SALES_FINANCINGS SF, SALESPERSONS SP, VEHICLES V
 WHERE S.saleID = SF.saleID AND S.vehicleVIN = V.vehicleCode AND S.salespersonID = SP.salespersonID
 GROUP BY vehicleVIN, saleDate, SF.planID, SP.dealerID
 HAVING COUNT(*) > 0;

BEGIN
FOR record IN sales_data
LOOP
    INSERT INTO SALES_FACTS (saleDay,vehicleCode,planID,dealerID,vehiclesSold, grossSalesAmt)
    VALUES (record.saleDate,record.vehicleVIN,record.planID,record.dealerID,record.vehiclesSold,record.grossSalesAmt);
END LOOP;
END;
/