sql 声明两个临时表,在运行更新查询时循环遍历两个数据集。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 声明两个临时表,在运行更新查询时循环遍历两个数据集。相关的知识,希望对你有一定的参考价值。

-- 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
	

以上是关于sql 声明两个临时表,在运行更新查询时循环遍历两个数据集。的主要内容,如果未能解决你的问题,请参考以下文章

SQL 查询优化

带有表变量的动态查询以循环遍历所有表以在数据库中更新

SQL 中将游标循环查询的结果插入到临时表中

将本地数据插入 SQL Server 临时表

循环遍历多个表的 plsql 代码

MySQL 存储过程,获取使用游标查询的结果集