title: SQL Query Get the Next ID
body: <p>I am working on a problem where I need to get the next available Category for a gamer. If the gamer has reached the final Category (Shooter in below image) then I will need to go back to the start of the table and go to the next one available.</p>
  <p>Below is a list of Category:</p>
  <p><a href="https://i.stack.imgur.com/Pdg60.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pdg60.png" alt="enter image description here" /></a></p>
  <p>Below is a list of gamers and what their last Category_ID was:</p>
  <p><a href="https://i.stack.imgur.com/5aqTr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5aqTr.png" alt="enter image description here" /></a></p>
  <p>Finally, below is the data I will be using to work with</p>
  <p><a href="https://i.stack.imgur.com/9vmLC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9vmLC.png" alt="enter image description here" /></a></p>
  <p>Now I need to find the next Category_ID for each gamer using the data table. If a Gamer has reached the last Category_ID (ID 4 in this case and Gamer C) then it will reset back to top like 1 however Gamer C will pick Category 2 as there is no one for that Gamer.</p>
  <p>How can I pick the next Category available using the data table for each gamer while keeping in mind of resetting back to top if reached end?</p>
  <p>Below is a code example of the problem:</p>
  <pre><code>DECLARE @Category AS TABLE
  (
      Category_ID INT IDENTITY(1,1) ,
      Description VARCHAR(255)
  )
  
  INSERT INTO @Category
  VALUES('Sports'), ('Adventure'), ('Action'), ('Shooter')
  
  DECLARE @Gamer AS TABLE
  (
      Username VARCHAR(255) ,
      Last_Category_ID INT
  )
  
  INSERT INTO @Gamer
  VALUES('Gamer A', 1), ('Gamer B', 2), ('Gamer C', 4), ('Gamer D', 3)
  
  DECLARE @Data AS TABLE
  (
      Username VARCHAR(255) ,
      Play_At DATETIME ,
      Category_ID INT
  )
  INSERT INTO @Data
  VALUES('Gamer A', GETDATE() -1, 1), ('Gamer B', GETDATE() -1, 2), ('Gamer A', GETDATE() -1, 3), ('Gamer D', GETDATE() -1, 3), ('Gamer C', GETDATE() -1, 2)
  
  
  SELECT * FROM @Category
  SELECT * FROM @Gamer
  SELECT * FROM @Data
  </code></pre>