我的数据库中有100000条记录,我需要在Batch中选择SELECT数据。因此,我需要在游标内实现批处理(每个select语句10000条记录),但我无法执行。 当我在没有CURSOR的情况下尝试相同的方法时,它可以正常工作,但在CURSOR的情况下却无法正常工作。可以让我知道我错过了什么。
DECLARE @user_id Varchar(50), @user_nid bigInt, @userId Varchar(50), @userNid bigInt;
DECLARE @id_control INT, @batchSize INT, @row_count INT
DECLARE @company_id Varchar(50),@company_nid bigInt;
SET @row_count = 1 -- Stores the row count after each successful batch
SET @batchSize = 10 -- How many rows you want to operate on each batch
SET @id_control = 0 -- Current batch
WHILE (@row_count > 0)
BEGIN
DECLARE user_cursor CURSOR FOR
SELECT row_number, user_nid, user_id FROM
(
SELECT DISTINCT user_nid, user_id, DENSE_RANK() OVER (ORDER BY user_nid) AS row_number
FROM users with (NOLOCK)
INNER JOIN sometable WITH (NOLOCK) ON user_nid = ui_frn_user_nid
WHERE
some condition goes here
) AS userVal
WHERE
row_number > @id_control
AND row_number <= @id_control + @batchSize
ORDER BY user_nid
OPEN user_cursor
FETCH NEXT FROM user_cursor
INTO @row_count, @user_nid, @user_id
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @row_count AS RC, @user_nid, @user_id, @id_control AS IC, @batchSize AS BATCHSZE;
FETCH NEXT FROM user_cursor
INTO @row_count, @user_nid, @user_id
END
SET @row_count = @@ROWCOUNT -- To obtain the latest rowcount to avoid infinite loops
SET @id_control = @id_control + @batchSize -- Next Batch
SELECT @row_count, @id_control;
END
CLOSE user_cursor;
DEALLOCATE user_cursor;
I have tried it without cursor and i am getting the expected result,but with cursor i am getting the exact data which i declare in @batchSize (for example if i give the size as @batchSize =10,i am getting only 10 records.),please some one let me know what i am missing out.