SelectNextFileToProcess.sql 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. CREATE PROCEDURE [dbo].[SelectNextFileToProcess]
  2. @serverId INT,
  3. @scriptInstanceId INT,
  4. @maxRetries INT,
  5. @mode NVARCHAR(50)
  6. AS
  7. BEGIN TRANSACTION
  8. -- Get the next row to process
  9. DECLARE @rowId INT = 0
  10. IF @mode = 'encrypt'
  11. BEGIN
  12. SELECT @rowId = Id
  13. FROM Files f
  14. WITH (TABLOCKX, HOLDLOCK)
  15. WHERE
  16. (f.[Status] = 1 OR f.[Status] = 4)
  17. AND f.[FileServerId] IN (SELECT [FileServerId] FROM [ServersFileServers] sfs WHERE sfs.ServerId = @serverId)
  18. AND (f.[AttemptCount] IS NULL OR f.[AttemptCount] < @maxRetries)
  19. ORDER BY f.[AttemptCount] DESC, f.[Id] ASC
  20. END
  21. IF @mode = 'decrypt'
  22. BEGIN
  23. SELECT @rowId = Id
  24. FROM Files f
  25. WITH (TABLOCKX, HOLDLOCK)
  26. WHERE
  27. (f.[Status] = 3 OR f.[Status] = 5)
  28. AND f.[FileServerId] IN (SELECT [FileServerId] FROM [ServersFileServers] sfs WHERE sfs.ServerId = @serverId)
  29. AND (f.[AttemptCount] IS NULL OR f.[AttemptCount] < @maxRetries)
  30. ORDER BY f.[AttemptCount] DESC, f.[Id] ASC
  31. END
  32. IF @rowId IS NOT NULL AND @rowId > 0
  33. BEGIN
  34. -- 'Lock' the row for processing by this script
  35. UPDATE Files
  36. SET [Status] = 2, [StartedWhen] = GETUTCDATE(), [InstanceId] = @scriptInstanceId
  37. WHERE [Id] = @rowId
  38. -- Get the row (with the label info + server status) to send back to the script
  39. SELECT f.*, l.[LabelGuid], l.[LabelName], s.IsActive, fs.FileServer, i.IsActive as InstanceActive
  40. FROM Files f
  41. LEFT JOIN Labels l on f.[LabelId] = l.Id
  42. LEFT JOIN Instances i on f.[InstanceId] = i.Id
  43. LEFT JOIN [Servers] s on i.ServerId = s.Id
  44. LEFT JOIN [FileServers] fs on fs.Id = f.FileServerId
  45. WHERE f.[Id] = @rowId
  46. END
  47. COMMIT