为两个查询编写存储过程,截断并插入两个不同的表

时间:2010-09-07 20:11:59

标签: sql

我在下面有两个问题。我如何将它们放在一个存储过程中。这两个查询都截断并在两个不同的表中插入记录。

QUERY 1

截断表[PlanFinder]。[InvalidAwps] 去

INSERT INTO [PlanFinder]。[InvalidAwps]

(Ndc, AwpUnitCost) 

SELECT DISTINCT P.Ndc Ndc, A.Price AwpUnitCost 

FROM 

    PlanFinder.PlanFinder.HpmsFormulary P 

    LEFT JOIN (SELECT Ndc, Price FROM MHSQL01D.Drug.FdbPricing.vNdcPrices  

               WHERE PriceTypeCode = '01' AND CurrentFlag = 1) A 

ON P.Ndc = A.Ndc  

WHERE (A.Ndc IS NULL OR A.Price <= 0 OR A.Price IS NULL) 

AND p.Ndc IS NOT NULL

查询2

截断表[PlanFinder]。[MissingNdcs] 去

INSERT INTO [PlanFinder]。[MissingNdcs]

(Ndc) 

SELECT DISTINCT Ndc 

FROM 

    PlanFinder.InvalidAwps   

WHERE AwpUnitCost IS NULL  

感谢并感谢任何帮助

1 个答案:

答案 0 :(得分:2)

取出GO语句并转储1 proc

中的所有代码
create procedure prBla
as

truncate table [PlanFinder].[InvalidAwps] 

INSERT INTO [PlanFinder].[InvalidAwps](Ndc, AwpUnitCost) 

SELECT DISTINCT P.Ndc Ndc, A.Price AwpUnitCost 
FROM 
    PlanFinder.PlanFinder.HpmsFormulary P 
    LEFT JOIN (SELECT Ndc, Price FROM MHSQL01D.Drug.FdbPricing.vNdcPrices  
               WHERE PriceTypeCode = '01' AND CurrentFlag = 1) A 
ON P.Ndc = A.Ndc  
WHERE (A.Ndc IS NULL OR A.Price <= 0 OR A.Price IS NULL) 
AND p.Ndc IS NOT NULL

truncate table [PlanFinder].[MissingNdcs] 
INSERT INTO [PlanFinder].[MissingNdcs] (Ndc) 

SELECT DISTINCT Ndc 
FROM  PlanFinder.InvalidAwps   
WHERE AwpUnitCost IS NULL  
GO

您可能想要添加一些错误处理...您想要做什么...如果其中一个语句失败,则回滚所有语句?