CREATE PROC [dbo].[SupplementaryInsurance_SaveData]
    @ComputerName NVARCHAR(MAX),
    @GoodsCode VARCHAR(15)
AS
--DELETE FROM ##DrugCondition
--WHERE GoodsCode = @GoodsCode
--      AND DifferAmount = 0
--      AND GoodsAmount = 0
--      AND NonInsuranceAmount = 0
--      AND GoodsAmount = 0
--      AND MessageId = 0
--      AND ComputerName = @ComputerName;

DELETE FROM dbo.SupplementaryInsurance_DrugCondition
WHERE InsuranceCode NOT IN (
                               SELECT InsuranceCode
                               FROM ##DrugCondition
                               WHERE GoodsCode = @GoodsCode
                                     AND ComputerName = @ComputerName
                           )
      AND GoodsCode = @GoodsCode;

INSERT INTO dbo.SupplementaryInsurance_DrugCondition
(
    GoodsCode,
    InsuranceCode,
    NonInsuranceAmount,
    PatientAmount,
    DifferAmount,
    GoodsAmount,
    MessageId
)
SELECT @GoodsCode,
       InsuranceCode,
       NonInsuranceAmount,
       PatientAmount,
       DifferAmount,
       GoodsAmount,
       MessageId
FROM ##DrugCondition
WHERE GoodsCode = @GoodsCode
      AND ComputerName = @ComputerName
      --AND (
      --        DifferAmount > 0
      --        OR GoodsAmount > 0
      --        OR NonInsuranceAmount > 0
      --        OR GoodsAmount > 0
      --        OR ##DrugCondition.MessageId > 0
      --    )
      AND InsuranceCode NOT IN (
                                   SELECT InsuranceCode
                                   FROM SupplementaryInsurance_DrugCondition
                                   WHERE GoodsCode = @GoodsCode
                               );

UPDATE SupplementaryInsurance_DrugCondition
SET NonInsuranceAmount = tdc.NonInsuranceAmount,
    PatientAmount = tdc.PatientAmount,
    DifferAmount = tdc.DifferAmount,
    GoodsAmount = tdc.GoodsAmount,
    MessageId = tdc.MessageId
FROM SupplementaryInsurance_DrugCondition dc
    JOIN ##DrugCondition tdc
        ON tdc.GoodsCode = dc.GoodsCode
           AND tdc.InsuranceCode = dc.InsuranceCode
WHERE dc.GoodsCode = @GoodsCode
      --AND (
      --        tdc.DifferAmount > 0
      --        OR tdc.GoodsAmount > 0
      --        OR tdc.NonInsuranceAmount > 0
      --        OR tdc.GoodsAmount > 0
      --        OR tdc.MessageId > 0
      --    );
