CREATE TRIGGER [dbo].[ForEShopGoods]
ON [dbo].[KalaId]
AFTER 
INSERT
, DELETE,
UPDATE
AS
    BEGIN
        Declare @EshopDel bit = (Select TOP 1 Eshop_Flag From Deleted)
		Declare @EshopIns bit = (Select TOP 1 Eshop_Flag From inserted)
		Declare @Action tinyint
		if update (Eshop_Flag) and (@EshopDel <> @EshopIns)
		begin
		  If @EshopIns = 1
			  Set @Action = 0
			Else
			  Set @Action = 1

		    INSERT dbo.EShopTablesChanges ( Id ,
                                            Name ,
                                            EntityRowId ,
                                            ModifiedOn ,
                                            Action )
                   SELECT NEWID() ,
                          'Goods' ,
                          Inserted.Id ,
                          GETDATE() ,
                          @Action
                   FROM   Inserted
            
             if @EshopIns=1 
		   begin
		     insert into dbo. EShopTablesChanges (id,
			 name,
			 EntityRowId,
			 ModifiedOn,
			 Action,
			 Fields
			 )
		     
			   SELECT NEWID() ,
                          'WarehouseGoods' ,
                          anbar.Id ,
                          GETDATE() ,
                          0,'WCode:'+A_Code
                   FROM   Anbar inner join inserted on inserted.K_Code=Anbar.K_Code
				   
    
		   end        
		end
        else IF EXISTS (   SELECT *
                          FROM   Inserted )
            INSERT dbo.EShopTablesChanges ( Id ,
                                            Name ,
                                            EntityRowId ,
                                            ModifiedOn ,
                                            Action )
                   SELECT NEWID() ,
                          'Goods' ,
                          Inserted.Id ,
                          GETDATE() ,
                          0
                   FROM   Inserted WHERE Inserted.Eshop_Flag=1
        ELSE IF EXISTS (   SELECT *
                               FROM   Deleted )
            INSERT dbo.EShopTablesChanges ( Id ,
                                            Name ,
                                            EntityRowId ,
                                            ModifiedOn ,
                                            Action )
                   SELECT NEWID() ,
                          'Goods' ,
                          Deleted.Id ,
                          GETDATE() ,
                          1
                   FROM   Deleted WHERE Deleted.Eshop_Flag=1 

    END
