如何在sql server中编写游标备用查询

时间:2017-08-20 02:52:38

标签: sql-server-2008 sql-server-2012

我需要在不使用游标的情况下实现。下面的脚本是使用光标,它需要5个小时才能获得140k记录。 如何提高sql server的性能?

原始表中的

有超过100k的记录。

SET NOCOUNT ON

CREATE TABLE #temp (
RecordID int identity,
Address varchar(50),
City varchar(30),
State varchar(5),
GPSLat numeric(9,6),
GPSLong numeric(9,6),
MapURL varchar(255))

INSERT INTO #temp (Address, City, State)
VALUES ('1033 Southwest 152nd Street', 'Burien', 'WA')

INSERT INTO #temp (Address, City, State)
VALUES ('11910 Northeast 154th Street', 'Brush Prairie', 'WA')

INSERT INTO #temp (Address, City, State)
VALUES ('500 SeaWorld Drive', 'San Diego', 'CA')

INSERT INTO #temp (Address, City, State)
VALUES ('1 Legoland Drive', 'Carlsbad', 'CA')


DECLARE curGeo CURSOR LOCAL STATIC FOR
SELECT RecordID, Address, City, State
FROM #temp

DECLARE @RecordID int
DECLARE @Address varchar(50)
DECLARE @City varchar(30)
DECLARE @State varchar(5)
DECLARE @GPSLatitude numeric(9, 6)
DECLARE @GPSLongitude numeric(9, 6)
DECLARE @MapURL varchar(255)

OPEN curGeo

FETCH curGeo INTO
    @RecordID,
    @Address,
    @City,
    @State

WHILE @@FETCH_STATUS = 0 BEGIN

    BEGIN TRY
        EXEC opsstream.sputilGeocode
            @Address = @Address OUTPUT,
            @City = @City OUTPUT,
            @State = @State OUTPUT,
            @GPSLatitude = @GPSLatitude OUTPUT,
            @GPSLongitude = @GPSLongitude OUTPUT,
            @MapURL = @MapURL OUTPUT


        UPDATE #temp
        SET
        GPSLat = @GPSLatitude,
        GPSLong = @GPSLongitude,
        MapURL = @MapURL
        WHERE
        RecordID = @RecordID

    END TRY
    BEGIN CATCH
        PRINT 'Warning: RecordID ' + CAST(@RecordID AS varchar(100)) + ' could not be geocoded.' 
    END CATCH


    FETCH curGeo INTO
        @RecordID,
        @Address,
        @City,
        @State
END

SELECT * FROM #temp

1 个答案:

答案 0 :(得分:0)

你的代码中有一个过程调用,所以我很确定问题不是游标,而是逐行逻辑完成的过程。您可以通过将其定义为fast_forward来提高游标的性能,但这可能并不明显。

您有一个程序可以调用,因此您需要更改程序以接受table valued parameter,然后当然要更改您的程序,使其不是逐行操作或将其更改为一个表值函数,但如果你使用多语句,它可能不会改善你的表现。