2

Here is a sample of the code I'm writing

DECLARE @totlunch int = 0;
DECLARE @totbreak int = 0;
DECLARE @over int = 0;


SELECT @totlunch = SUM(CASE when [StatusKey] = 'at lunch' then StateDuration else 0 end),
        @totbreak = SUM(CASE when [StatusKey] = 'break' then StateDuration else 0 end) 
  FROM [I3_IC].[dbo].[AgentActivityLog]
  WHERE UserId in ('mdavila')
    AND StatusDateTime between '2014-08-28 00:00:00' AND '2014-08-28 23:59:59'
  --group by UserId

  print @totlunch;
  print @totbreak;

  if(@totlunch > 3600)BEGIN
    SET @over = @over + (@totlunch - 3600);
  END

  if(@totbreak > 1800)BEGIN
    SET @over = @over + (@totbreak - 1800);
  END

  print @over;  

I want to do this task for a group of "UserId"s, insterad of juat "mdavila" but I'm not sure how to loop it as SQL queries seem to not support arrays. Any help in how I can accomplish this task would be greatly appreciated. Thanks!

Please note that I need to keep track of each user individually. I will populate a temp table with the data I want, but I just need to know a way of looping this code for a group of users.

3
  • what rdbms are you using? Commented Sep 11, 2014 at 23:57
  • 1
    Is this SQL Server, Oracle, MySQL? Commented Sep 12, 2014 at 0:06
  • ok, see my answer below. Commented Sep 12, 2014 at 15:42

1 Answer 1

5

If you are using SQL Server, you can use a Table variable to loop through records.

I have simplified it here to show you the concept - it should be enough to get you started.

-- Table variable to store the list of user ID
declare @UserIds table (UserId INT) 
declare @CurrentUserID INT

-- Load the table with the list of users we want to work with
INSERT INTO @UserIds (UserId)
SELECT userid
FROM AgentActivityLog   

-- loop through each user
WHILE EXISTS (SELECT UserId FROM @UserIds)
BEGIN

    -- select a user from the list of users
    SELECT TOP 1 @CurrentUserID = UserId 
    FROM @UserIds
    ORDER BY UserId ASC

    -- Do stuff with @CurrentUserID

   --Remove the current user id from the table variable - we are done with it
   DELETE FROM @UserIds WHERE UserId = @CurrentUserID
END
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly! Thanks Donal! This site is great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.