CREATE PROCEDURE DBO.OwnerGetOwnerWareNumber @AProductNumber INT, @AOwnerType INT, @ResultAccountNumber INT OUTPUT AS

/*
  Created by Kent Johansen January 2007

  Changes:
    KJ 20100920: Added AOwnertype (Logi, OwnerElectricity, OwnerCleaning, OwnerAdditional)
    KJ 20070427: Bug: Fix for "Returnvalue was accountnumber - should be warenubmer"

*/

IF @AOwnerType = 0 -- Logi
BEGIN
  DECLARE @ProductTypeNumber INT
  DECLARE @TypeNumber INT
  DECLARE @Index INT

  SET @Index = 1

  SELECT @ProductTypeNumber = ProductTypeNumber FROM Products WITH (NOLOCK) WHERE ProductNumber = @AProductNumber

  DECLARE ProductTypeCur CURSOR FAST_FORWARD READ_ONLY FOR
    SELECT ProductTypeNumber FROM ProductTypes WITH (NOLOCK) ORDER BY SortNumber
  OPEN ProductTypeCur

  FETCH NEXT FROM ProductTypeCur INTO @TypeNumber

  WHILE (@@Fetch_Status=0)
  BEGIN
    IF (@TypeNumber <> @ProductTypeNumber)
    BEGIN
      SET @Index = @Index + 1
      FETCH NEXT FROM ProductTypeCur INTO @TypeNumber
    END
    ELSE
     BREAK
  END

  CLOSE ProductTypeCur
  DEALLOCATE ProductTypeCur

  DECLARE WareCur CURSOR SCROLL READ_ONLY FOR
    SELECT
      Ware.WareNumber
    FROM Ware WITH (NOLOCK) 
    INNER JOIN WareGroups WITH (NOLOCK) ON Ware.WareGroupNumber =  WareGroups.WareGroupNumber
    WHERE WareGroups.Payment=2 AND Ware.MarkAsDeleted IS NULL
    ORDER BY Ware.SortNumber
  OPEN WareCur

  FETCH ABSOLUTE @Index FROM WareCur INTO  @ResultAccountNumber

  CLOSE WareCur
  DEALLOCATE WareCur
END
ELSE
BEGIN
  SELECT @ResultAccountNumber = WareNumber 
  FROM Ware WITH (NOLOCK) 
  WHERE Type = (@AOwnerType + 6)
  AND ISNULL(MarkAsDeleted, 0) = 0
    
  SET @ResultAccountNumber = ISNULL(@ResultAccountNumber, 0)
END 

