我正在使用以下查询。我正在从一张桌子到另一张桌子移动1000行。 但是,它只是传输交替的1000行,就是这样。
如果删除cte子句,我会获得完整数据。你能告诉我哪里错了吗?
DECLARE @BatchSize INT = 1000
DECLARE @Counter INT = 0
DECLARE @TableCount INT = 0
set @TableCount = (select count(*) from TableSource)
print @TableCount/@BatchSize //10000/1000
while @Counter < (@TableCount/@BatchSize+1)
BEGIN
INSERT INTO TableDest
SELECT *
FROM TableSource MH
inner join Table1 M
on MH.Mid = M.Mid
order by HID OFFSET (@BatchSize * @Counter)ROWS FETCH NEXT @Batchsize ROWS ONLY;
with cte as
(
SELECT HID
FROM TableSource MH
inner join Table1 M
on MH.Mid = M.Mid
order by message_history_id OFFSET (@BatchSize * @Counter)ROWS FETCH NEXT @Batchsize ROWS ONLY
)
delete from TableSource where HID IN (select cte.HID from cte)
SET @Counter=@Counter+1;
END
为什么只插入1000行?
It only transfers following rows if the total rows are 10,000:
0-1000
2001-3000
4001-5000
6001-7000
8001-9000
我有大量数据,所以我这样做。我不想锁定整个表格,因此我无法选择或删除所有内容。
答案 0 :(得分:0)
这是因为您在复制后从源表中删除了前1000行。下次再次应用1000偏移时。将cte子句移到循环外部并立即删除所有内容,你应该没问题。
编辑:其他选项是删除插入和放大的偏移量。删除语句并在循环中保留cte子句。
答案 1 :(得分:0)
从选择中删除计数器
DECLARE @BatchSize INT = 1000
DECLARE @Counter INT = 0
DECLARE @TableCount INT = 0
set @TableCount = (select count(*) from TableSource)
print @TableCount/@BatchSize //10000/1000
while @Counter < (@TableCount/@BatchSize+1)
BEGIN
INSERT INTO TableDest
SELECT *
FROM TableSource MH
inner join Table1 M
on MH.Mid = M.Mid
order by HID OFFSET (0/* REMOVED@BatchSize * @Counter */)ROWS FETCH NEXT @Batchsize ROWS ONLY;
with cte as
(
SELECT HID
FROM TableSource MH
inner join Table1 M
on MH.Mid = M.Mid
order by message_history_id OFFSET (0/* REMOVED@BatchSize * @Counter*/)ROWS FETCH NEXT @Batchsize ROWS ONLY
)
delete from TableSource where HID IN (select cte.HID from cte)
SET @Counter=@Counter+1;
END