﻿CREATE PROCEDURE [dbo].[sp_LockFree]     
	@UserId							INT				= NULL
	,@UserName						NVARCHAR(50)	= NULL
	,@ItemId						BIGINT			= NULL
	,@CategoryId					INT
    ,@errorNumber					INT				OUTPUT
    ,@errorMessage					NVARCHAR(250)	OUTPUT     
AS
BEGIN
 SET @errorNumber = 0 
 SET @errorMessage = space(0)
 
 IF(@UserId) IS NULL
 BEGIN
  IF NOT EXISTS( SELECT ID FROM Users WHERE UserName=@UserName)
  BEGIN
   SET @errorNumber = 2
   SET @errorMessage = 'User not found'
   return -1
  END
 END

 IF NOT EXISTS( SELECT LockId FROM LockedItems WHERE CategoryId=@CategoryId AND ItemId=@ItemId)
 BEGIN
  SET @errorNumber = 3
  SET @errorMessage = 'No lock to free'
  return -1
 END
 ELSE
 BEGIN  
  DECLARE @UpdateTime DateTime
	DELETE from LockedItems WHERE CategoryId=@CategoryId AND ItemId=@ItemId
 END
END