CREATE PROC [dbo].[UpdatePriceNonInsurance]
    @ComputerName NVARCHAR(30),
    @OrgCode VARCHAR(MAX),
    @IsAdvanced BIT
AS
--------------------------------Update Darou Flag Kalaid Table
UPDATE dbo.KalaId
SET Darou_Flag = 6
FROM dbo.KalaId G
    JOIN ##tmpView tmp
        ON tmp.K_Code COLLATE Arabic_CI_AS = G.K_Code
WHERE G.Darou_Flag = 0
      AND
      (
          (
              @IsAdvanced = 0
              AND tmp.UpdateStatus = 1
          )
          OR
          (
              @IsAdvanced = 1
              AND tmp.UpdateStatus = 0
          )
      )
      AND tmp.Computer_Name = @ComputerName;
---------------------------------Insert Into  Price Sazman Table
INSERT INTO dbo.Price_Sazman
(
    K_Code,
    Sazman_Code,
    Price,
    Status,
    BimarPercent
)
SELECT tmp.K_Code,
       Insurance.Code,
       CASE
           WHEN tmp.Price <= tmp.Old_Price THEN
               tmp.Price
           ELSE
               tmp.Old_Price
       END,
       CASE
           WHEN tmp.[PERCENT] = -100 THEN
               4
           ELSE
               6
       END,
       CASE
           WHEN tmp.[PERCENT] = -100 THEN
               0
           ELSE
               tmp.[Percent]
       END
FROM ##tmpView tmp
    CROSS APPLY
(
    SELECT splitdata Code
    FROM dbo.fnSplitString(@OrgCode, ',')
) AS Insurance
    LEFT JOIN Price_Sazman OP
        ON OP.K_Code COLLATE Arabic_CI_AS = tmp.K_Code
           AND OP.Sazman_Code COLLATE Arabic_CI_AS = Insurance.Code
WHERE (
          (
              @IsAdvanced = 0
              AND tmp.UpdateStatus = 1
          )
          OR
          (
              @IsAdvanced = 1
              AND tmp.UpdateStatus = 0
          )
      )
      AND Computer_Name = @ComputerName
      AND tmp.K_Code NOT IN
          (
              SELECT K_Code
              FROM ##tmpView tv
              WHERE (
                        @IsAdvanced = 0
                        AND tmp.UpdateStatus = 1
                    )
                    OR (
                           @IsAdvanced = 1
                           AND tmp.UpdateStatus = 0
                       )
                       AND Computer_Name = @ComputerName
              GROUP BY tv.K_Code
              HAVING COUNT(tv.K_Code) > 1
          )
      AND
      (
          tmp.Darou_flag = 0
          OR
          (
              tmp.Darou_flag = 6
              AND (OP.K_Code IS NULL)
          )
      );