我有一个存储过程,它运行一个select语句,返回一行并将内容插入临时表。select语句在where子句中有6个条件语句,我基本上需要循环3组附加条件并将这些结果插入temp表。到目前为止,我掌握的情况如下:
CREATE DEFINER=`sleuser`@`%` PROCEDURE `CostDashboard`()
BEGIN
create temporary table TempTable (
ProjectID int,
Phase varchar(100),
OriginalCommitments float,
ApprovedCommitmentChanges float,
CurrentAssigned float,
PendingScopeChanges float,
EAC float,
PercentComplete float
);
insert into TempTable(
SELECT project_id,
'FP' as Phase,
OriginalCommitments,
ApprovedCommitmentChanges,
OriginalCommitments+ApprovedCommitmentChanges as CurrentAssigned,
sum(ProjectCostBudget.PendingChangeOrders) as PendingScopeChanges
sum(ProjectCost.CurrentWorkCompleted) +
sum(ProjectCost.EstimateToComplete) as EAC,
(sum(ProjectCost.CurrentWorkCompleted) +
sum(ProjectCost.EstimateToComplete) /
(sum(ProjectCostBudget.OriginalContractPrice +
ProjectCostBudget.RegisteredChangeOrders))) as PercentComplete
FROM `RCLY-DEV`.project
inner join ImportCost on ImportCost.ProjectID = project.pmis
inner join ProjectCostBudget on ProjectCostBudget.ProjectID =
project.project_id
inner join ProjectCost on ProjectCost.ProjectID = project.project_id
where ImportCost.ProjectID = 'RLCY-BB-01'
and ImportCost.Task = "020.0000.000"
and ProjectCostBudget.ProjectID = 2
and ProjectCostBudget.ServiceNumber = "020.0000.000"
and ProjectCost.MonthYear != ''
and ProjectCost.MonthYear like 'July%2018'
);
select * from TempTable
;
END
这样可以在where子句中插入一条带有硬编码值的记录,但我需要对3组变量运行它,因此我创建了一个额外的临时表,如下所示:
|ImpCostID|ImpCostTask |PCBID|PCBServNum |MonthYear|
-----------------------------------------------------
|XXY-01-01|030.0000.000|3 |030.0000.000|July%2018|
|QWY-01-01|040.0000.000|4 |040.0000.000|May%2018 |
|ZXF-01-01|040.0000.000|5 |050.0000.000|June%2018|
但我不知道如何将这些值集赋给变量,然后循环遍历它们。有什么建议吗?
2条答案
按热度按时间rqenqsqc1#
尽可能避免对sql语句进行序列化(这可能代价高昂)。在这种情况下,您可以简单地使用参数表与实际查询的联接。如果你只是用临时表
TempTable
要为您保存结果,您也不需要这样做,因为您可以在一个查询中获得所有结果:kr98yfug2#
如果我能正确理解你的问题,那么下面的问题就解决了。
创建具有标识列的临时表,然后在其中插入数据。如果临时表没有唯一的列,这将有助于循环遍历每条记录