代码之家  ›  专栏  ›  技术社区  ›  franchesco totti

低速SQL查询

  •  1
  • franchesco totti  · 技术社区  · 10 年前

    我在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
    
    1 回复  |  直到 10 年前
        1
  •  2
  •   marc_s WardL    10 年前

    试试这样的- 避免 任何 一排排痛苦的排 类似光标或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
    

    那应该 明显地 加快处理时间!