tags:

views:

17

answers:

1

Hi All,

I have two queries below. how do i put them in one stored proc. both the queries are truncating and inserting records in two different tables.

QUERY 1

truncate table [PlanFinder].[InvalidAwps] go

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

Query 2

truncate table [PlanFinder].[MissingNdcs] go

INSERT INTO [PlanFinder].[MissingNdcs]

(Ndc) 

SELECT DISTINCT Ndc 

FROM 

    PlanFinder.InvalidAwps   

WHERE AwpUnitCost IS NULL  

Thanks and Appreciate any help

+2  A: 

take out the GO statements and dump all the code in 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

you might want to add some error handling...what do you want to do...rollback all if one of the statements fails or not?

SQLMenace
ohh, so i just had to take out GO, thats y i was getting an error. thanks appreciate it.
CombatCaptain
to clarify and/or explain: go ends a block of sql statements and submits it for execution. This is not needed in a stored procedure, since it is and has to be a single block of code. The go needs to be after the end of the create procedure statement and not inside it.
Rawheiser
thanks. appreciate it.
CombatCaptain
DOn't forget Denis's question about error handling and rollback, this is critically important when you insert into more than one table. YOu need to have this is a transaction that rolls back if part of it fails.
HLGEM