SQL FETCH and WHILE looper to insert and select
I needed to do a looper in SQL to subquery all the users related to old system. This is what I came up with:
First of all I need to get all the leads related to one user and what group that user is in, then fron the leadid and groupid I needed to find all the users in the group to add to the lead. What fun
DECLARE @GetLeads TABLE (GroupID int, LeadID int, UserID uniqueidentifier)
DECLARE @GetUsers TABLE (LeadID int, UserID uniqueidentifier)
DECLARE ThisGroupID CURSOR FOR
SELECT [ID]
FROM [spot].[dbo].[LeadInfo]
DECLARE @MasterId Int
DECLARE @SubMasterGroup int
DECLARE @SubMasterLead int
DECLARE @SubUser uniqueidentifier
DECLARE @SubLead int
OPEN ThisGroupID;
FETCH NEXT FROM ThisGroupID
INTO @MasterId
INSERT INTO @GetLeads
SELECT (SELECT TOP 1[GroupID] FROM [spot].[dbo].[GroupRoles] WHERE [UserID] = [spot].[dbo].[LeadsRoles].[RoleID] ) As GroupID, [LeadID], [RoleID] FROM [spot].[dbo].[LeadsRoles] WHERE [LeadID] = @MasterId
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM ThisGroupID INTO @MasterId
INSERT INTO @GetLeads
SELECT (SELECT TOP 1[GroupID] FROM [spot].[dbo].[GroupRoles] WHERE [UserID] = [spot].[dbo].[LeadsRoles].[RoleID] )As GroupID, [LeadID], [RoleID] FROM [spot].[dbo].[LeadsRoles] WHERE [LeadID] = @MasterId
END;
CLOSE ThisGroupID;
DEALLOCATE ThisGroupID;
DELETE FROM @GetLeads WHERE GroupID IS NULL
DECLARE ThisLeadGroupID CURSOR FOR
SELECT [GroupID], [LeadID] FROM @GetLeads
OPEN ThisLeadGroupID;
FETCH NEXT FROM ThisLeadGroupID
INTO @SubMasterGroup, @SubMasterLead
INSERT INTO @GetUsers (LeadID, UserID)
(SELECT DISTINCT (@SubMasterLead)AS LeadID,[UserID] FROM [spot].[dbo].[GroupRoles] WHERE [GroupID] = @SubMasterGroup)
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM ThisLeadGroupID
INTO @SubMasterGroup, @SubMasterLead
INSERT INTO @GetUsers (LeadID, UserID)
(SELECT DISTINCT (@SubMasterLead)AS LeadID,[UserID] FROM [spot].[dbo].[GroupRoles] WHERE [GroupID] = @SubMasterGroup)
END;
CLOSE ThisLeadGroupID;
DEALLOCATE ThisLeadGroupID;
INSERT INTO [spot].[dbo].[LeadsRoles] (LeadID, RoleID)
SELECT * FROM @GetUsers
GO