Bugsta
Bugsta

Reputation: 51

SQL query – doing a loop but using an array of variables

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.

Upvotes: 2

Views: 9858

Answers (1)

Donal
Donal

Reputation: 32723

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

Upvotes: 5

Related Questions