DECLARE @ORDRNO VARCHAR(10) = '%ordrno%'
DECLARE @ITEM   VARCHAR(10) = '%itemno%'
DECLARE @NEWQTY VARCHAR(10) = '%qty%'
DECLARE @USER   VARCHAR(10) = '%user%'
DECLARE @DT     DATETIME = GETDATE()
DECLARE @OLDQTY INTEGER = 0 
DECLARE @INSERT TINYINT = 0

SELECT @OLDQTY = [Qty_ Ordered] FROM [KITCHEN FRESH FOODS$Sales line import] WHERE [Document Type] = 1 and [Document No_] = @ORDRNO and[Item No_] = @ITEM

IF @@ROWCOUNT = 0 AND @NEWQTY > 0 SET @INSERT = 1

IF @INSERT = 1
   INSERT INTO [KITCHEN FRESH FOODS$sales line import]
               ([document type],[Document No_],[line no_],[qty_ ordered],[qty_ shipped],[Qty_ to Make],[Qty_ to Bin],[Original Qty_ ordered],[SBT Last Modified],[SBT Added],[SBT Added By],[SBT Last Modified By],
                [Sell-to Customer No_],[item no_])
        VALUES (1,@ORDRNO,(case PATINDEX('%[^A-Za-z]%', LEFT(@ITEM,1)) when 0 then SUBSTRING(@ITEM,2,5) else @ITEM END)+'00',@NEWQTY,@NEWQTY,@NEWQTY,@NEWQTY,@NEWQTY,@DT,@DT,@USER,@USER,
                (SELECT TOP (1) H.[SELL-TO CUSTOMER NO_] FROM [kitchen fresh foods$Sales header import] H WHERE [DOCUMENT TYPE]= 1 AND [DOCUMENT NO_] = @ORDRNO ORDER BY H.[Document No_]),
                (SELECT TOP (1) I.[No_] FROM [Kitchen Fresh Foods$Item] I WHERE [No_] = @ITEM ORDER BY I.No_))  

ELSE
	UPDATE [KITCHEN FRESH FOODS$Sales line import]
	   SET [Qty_ Shipped] = @NEWQTY,
		   [Qty_ Ordered] = @NEWQTY,
		   [Qty_ to Make] = @NEWQTY,
		   [Qty_ to Bin]  = @NEWQTY,
		   [SBT Last Modified] = @DT,
		   [SBT Last Modified By] = @USER
	 WHERE [Document Type] = 1 and 
		   [Document No_] = @ORDRNO and
		   [Item No_] = @ITEM


UPDATE [KITCHEN FRESH FOODS$Sales Header Import]
   SET [open] = 1,
       [SBT Last Modified] = @DT,
       [SBT Last Modified By] = @USER,
       [delivery trays qty] = (SELECT CEILING(ISNULL((SELECT SUM(L.[Qty_ Ordered]/I.[Qty_ per Unit of Measure]) 
                               from [KITCHEN FRESH FOODS$Sales Line Import] l
                               join [KITCHEN FRESH FOODS$Item unit of measure] i on i.[Item No_]  = l.[item no_] and i.[code] = 'TRAY'
                               WHERE L.[Document No_] = @ORDRNO AND L.[Document Type] = 1),0)*10)/10)
   WHERE [document type] = 1 and [document no_] = @ORDRNO

/*
IF @NEWQTY <> @OLDQTY
INSERT INTO [WC].[DBO].[Order Details] (DateTime,[Document No],[Item No],[New Qty],[Old Qty]) VALUES (@DT,@ORDRNO,@ITEM,@NEWQTY,@OLDQTY)
*/