CREATE PROC [dbo].[ExclusiveInsuranceCode_Save]
    @ComputerName NVARCHAR(MAX),
    @GoodsCode VARCHAR(17)
AS
UPDATE ##ExclusiveInsuranceCode
SET Id = NULL
WHERE ISNULL(Code, '') = ''
      OR SalesCeiling = 0;
DELETE FROM dbo.ExclusiveInsuranceCode
WHERE GoodsCode = @GoodsCode
      AND Id NOT IN
          (
              SELECT Id
              FROM ##ExclusiveInsuranceCode
              WHERE Id IS NOT NULL
                    AND GoodsCode = @GoodsCode
                    AND ComputerName = @ComputerName
          );
-----------------------------------------------------------
INSERT INTO ExclusiveInsuranceCode
(
    Id,
    Code,
    InsuranceCode,
    GoodsCode,
    SalesCeiling,
	HasTTAC
)
SELECT NEWID(),
       Code,
       InsuranceCode,
       GoodsCode,
       SalesCeiling,
	   HasTTAC
FROM ##ExclusiveInsuranceCode
WHERE (
          ISNULL(Code, '') <> ''
          OR SalesCeiling > 0
      )
      AND ISNULL(Id, NEWID()) NOT IN
          (
              SELECT Id FROM ExclusiveInsuranceCode
          )
      AND GoodsCode = @GoodsCode
      AND ComputerName = @ComputerName;
-------------------------------------------------------------
UPDATE ExclusiveInsuranceCode
SET SalesCeiling = tmp.SalesCeiling,
    Code = tmp.Code,
	HasTTAC = tmp.HasTTAC
FROM ExclusiveInsuranceCode
    JOIN ##ExclusiveInsuranceCode tmp
        ON tmp.Id = ExclusiveInsuranceCode.Id
           AND ComputerName = @ComputerName
           AND ExclusiveInsuranceCode.GoodsCode = @GoodsCode;