SelectNextBatchToProcess.sql 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 
  2. CREATE PROCEDURE [dbo].[SelectNextBatchToProcess]
  3. @serverId INT,
  4. @scriptInstanceId INT,
  5. @maxRetries INT,
  6. @mode NVARCHAR(50),
  7. @batchSize INT
  8. AS
  9. BEGIN
  10. DECLARE @status TABLE (Id INT)
  11. IF @mode = 'encrypt'
  12. BEGIN
  13. INSERT INTO @status (Id)
  14. VALUES (1), (4)
  15. END
  16. IF @mode = 'decrypt'
  17. BEGIN
  18. INSERT INTO @status (Id)
  19. VALUES (3), (5)
  20. END
  21. DECLARE @rowIds TABLE (Id INT PRIMARY KEY)
  22. -- 'Lock' the rows for processing by this script
  23. UPDATE f_
  24. SET
  25. [Status] = 2,
  26. [StartedWhen] = GETUTCDATE(),
  27. [InstanceId] = @scriptInstanceId
  28. OUTPUT
  29. inserted.Id
  30. INTO @rowIds
  31. FROM
  32. (
  33. SELECT TOP (@batchSize) *
  34. FROM Files f
  35. WHERE
  36. f.[Status] IN (SELECT * FROM @status)
  37. AND EXISTS
  38. (
  39. SELECT 1
  40. FROM [ServersFileServers] sfs
  41. WHERE
  42. sfs.ServerId = @serverId
  43. AND sfs.[FileServerId] = f.[FileServerId]
  44. )
  45. AND f.[AttemptCount] < @maxRetries
  46. ORDER BY
  47. f.[AttemptCount] ASC,
  48. f.[Id] ASC
  49. ) f_
  50. DECLARE @rowCount INT = @@ROWCOUNT
  51. IF (@rowCount > 0)
  52. BEGIN
  53. -- Get the rows (with the label info + server status) to send back to the script
  54. SELECT f.*, l.[LabelGuid], l.[LabelName], s.IsActive, fs.FileServer, i.IsActive as InstanceActive
  55. FROM Files f
  56. LEFT JOIN Labels l ON l.Id = f.[LabelId]
  57. LEFT JOIN Instances i ON i.Id = f.[InstanceId]
  58. LEFT JOIN [Servers] s ON s.Id = i.ServerId
  59. LEFT JOIN [FileServers] fs ON fs.Id = f.FileServerId
  60. WHERE
  61. f.[Id] IN (SELECT Id FROM @rowIds)
  62. END
  63. END