我在SQL Server中有16000行,我想在物理上为记录分配文档编号并使用以下代码,当我的记录为8000时它工作正常但很懒但当记录增加到16000时它会给我一个超时错误,请帮我提高查询性能???
declare @NewDoc int;
set @NewDoc=0
declare t1_cursor cursor dynamic for select documentheaderid,documentnumber from Accounting.DocumentHeader where FinancialPeriodFK=@FinancialPeriodFK and Date>=@FromDate and Date<=@ToDate order by Date
open t1_cursor
fetch next from t1_cursor
while(@@fetch_status=0)
begin
set @NewDoc=@NewDoc+1;
update Accounting.DocumentHeader set DocumentNumber=@NewDoc where current of t1_cursor
fetch next from t1_cursor
end
close t1_cursor
deallocate t1_cursor
答案 0 :(得分:2)
尝试类似这样的事情 - 避免任何逐行激动行处理,如游标或while循环:
-- creates a temporary "inline" view of the data you're interested in and
-- assigns each row a consecutive number
;WITH DataToUpdate AS
(
SELECT
DocumentHeaderId,
DocumentNumber,
NewDocNum = ROW_NUMBER() OVER(ORDER BY [Date])
FROM
Accounting.DocumentHeader
WHERE
FinancialPeriodFK = @FinancialPeriodFK
AND Date >= @FromDate
AND Date <= @ToDate
)
-- update the base table to make use of that new document number
UPDATE dh
SET dh.DocumentNumber = dtu.NewDocNum
FROM Accounting.DocumentHeader dh
INNER JOIN DataToUpdate dtu ON dh.DocumentHeaderId = dtu.DocumentHeaderId
应该显着加快处理时间!