/*
BEGIN TRAN
SELECT CONVERT(FLOAT, Row_Number() OVER (Order By PK_CashBox)) AS RecNo,
* FROM Cashbox WITH (NOLOCK)
WHERE MarkAsDeleted IS NULL AND Name <> 'System'
ORDER BY PK_CashBox
*/
IF NOT EXISTS
(
  SELECT SysColumns.Name 
  FROM SysObjects WITH (NOLOCK) 
    INNER JOIN SysColumns WITH (NOLOCK) ON SysColumns.Id = SysObjects.ID 
    AND SysColumns.Name = 'CashIdentityIndex'
    WHERE SysObjects.Name = 'CashBox'
)
  ALTER TABLE CashBox ADD CashIdentityIndex INT NULL 
IF NOT EXISTS
(
  SELECT SysColumns.Name 
  FROM SysObjects WITH (NOLOCK) 
    INNER JOIN SysColumns WITH (NOLOCK) ON SysColumns.Id = SysObjects.ID 
    AND SysColumns.Name = 'CashId'
    WHERE SysObjects.Name = 'Invoices'
)
  ALTER TABLE Invoices ADD CashId INT NULL 
IF NOT EXISTS
(
  SELECT SysColumns.Name 
  FROM SysObjects WITH (NOLOCK) 
    INNER JOIN SysColumns WITH (NOLOCK) ON SysColumns.Id = SysObjects.ID 
    AND SysColumns.Name = 'CashId'
    WHERE SysObjects.Name = 'CanceledBillNumbers'
)
  ALTER TABLE CanceledBillNumbers ADD CashId INT NULL 
IF NOT EXISTS
(
  SELECT SysColumns.Name 
  FROM SysObjects WITH (NOLOCK) 
    INNER JOIN SysColumns WITH (NOLOCK) ON SysColumns.Id = SysObjects.ID 
    AND SysColumns.Name = 'CashId'
    WHERE SysObjects.Name = 'Invoice'
)
  ALTER TABLE Invoice ADD CashId INT NULL 
GO
DECLARE @Counter INT, @PkCashBox INT
SELECT @Counter = MAX(ISNULL(CashIdentityIndex, 0)) FROM Cashbox WITH (NOLOCK) 
SET @PkCashBox = 0
WHILE (SELECT Count(*) FROM Cashbox WITH (NOLOCK) WHERE ISNULL(CashIdentityIndex, 0)=0 AND MarkAsDeleted IS NULL AND Name <> 'System') > 0 
BEGIN  
  SELECT TOP 1 @PkCashBox = PK_CashBox FROM Cashbox WITH (NOLOCK) 
  WHERE ISNULL(CashIdentityIndex, 0)=0 AND MarkAsDeleted IS NULL AND Name <> 'System'
  ORDER BY PK_CashBox
  IF NOT @PkCashBox IS NULL
    UPDATE CashBox SET CashIdentityIndex = @Counter+1 WHERE PK_CashBox=@PkCashBox
  SET @Counter = @Counter + 1
END
/*
SELECT CONVERT(FLOAT, Row_Number() OVER (Order By PK_CashBox)) AS RecNo,
* FROM Cashbox WITH (NOLOCK)
WHERE MarkAsDeleted IS NULL AND Name <> 'System'
ORDER BY PK_CashBox
ROLLBACK TRAN
*/