johnbocook
3/7/2016 - 5:07 PM

Declare two temporary tables, loop over both data-sets while running update query.

Declare two temporary tables, loop over both data-sets while running update query.

-- Created 3/7/2016
-- Author: John Bocook
-- Updates prospects agencies. Loops user id's and selects new agency_cod round robin style.

DECLARE @ids table(tmp_rid int identity(1,1), soc_sec VARCHAR(9), agency CHAR(10))
DECLARE @recruiters table(rec_tmp_rid int identity(1,1), agency CHAR(10))

INSERT INTO @ids (soc_sec)
	-- Change select query to pull your user ids
	SELECT soc_sec FROM prospect WHERE agency_cod like 'something'

INSERT INTO @recruiters(agency)
	-- Recruiter list to be used for reassigning
	VALUES ('recruiter1'),('recruiter2')

DECLARE @ids_i int
DECLARE @ids_cnt int

DECLARE @rec_i int
DECLARE @rec_cnt int

-- Set counts for looping
SELECT @ids_i = min(tmp_rid) - 1, @ids_cnt = max(tmp_rid) FROM @ids
SELECT @rec_i = min(rec_tmp_rid) - 1, @rec_cnt = max(rec_tmp_rid) FROM @recruiters

WHILE @ids_i < @ids_cnt

	BEGIN
		IF @rec_i < @rec_cnt
			BEGIN
				SELECT @rec_i = @rec_i + 1
			END
		ELSE
			BEGIN
				SELECT @rec_i = 1
			END
			
		SELECT @ids_i = @ids_i + 1
		
		-- Table update query
		UPDATE prospect
			SET agency_cod = (SELECT agency FROM @recruiters WHERE rec_tmp_rid = @rec_i),
				operator = 'jbocook',
				date_maint = '2016-03-07 00:00:00.000'
		WHERE soc_sec = (SELECT soc_sec from @ids WHERE tmp_rid = @ids_i)
		-- END table update query

	END