了解游标的工作原理

时间:2018-07-23 18:50:25

标签: sql-server tsql

尝试更改某些存储过程和查询以提高性能。在某种程度上,它重写了游标语法。为此,我必须充分了解它们的工作原理。我尝试了这个简单的ETL示例,但没有得到预期的结果。基本上,在这里使用游标执行UPSERT。

示例代码:

CREATE TABLE #Destination 
(PersonID INT, FirstName VARCHAR(10), LastName VARCHAR (10))
 INSERT INTO #Destination VALUES (101, 'M', 'Donalds')
 INSERT INTO #Destination VALUES (102, NULL, 'Richards')
 INSERT INTO #Destination VALUES (103, 'Rianna', 'Lock')
 INSERT INTO #Destination VALUES (104, 'Leo', 'Svensson')

 CREATE TABLE #SourceTable 
 (PersonID INT, FirstName VARCHAR(10), LastName VARCHAR (10))
 INSERT INTO #Destination VALUES (102, 'Diana', 'Richards')
 INSERT INTO #SourceTable VALUES (103, 'Rianna', 'Locks')
 INSERT INTO #SourceTable VALUES (106, 'Cleo', 'Davung')

  DECLARE @PersonID INT
  DECLARE @Firstname VARCHAR (10)
  DECLARE @Lastname VARCHAR (10)

  DECLARE SimpleCursor CURSOR FOR 
  SELECT PersonID, FirstName, LastName 
  FROM #SourceTable

  Open SimpleCursor
  FETCH NEXT FROM SimpleCursor INTO @PersonID, @Firstname, @Lastname
  WHILE @@FETCH_STATUS = 0 
  BEGIN
  IF EXISTS ( SELECT PersonID FROM #Destination
              WHERE PersonID = @PersonID )
    UPDATE #Destination  
    SET #Destination.FirstName = #SourceTable.FirstName,
        #Destination.LastName = #SourceTable.LastName
    FROM #SourceTable
    WHERE #Destination.PersonID = #SourceTable.PersonID
  ELSE
    INSERT INTO #Destination
    SELECT PersonID, Firstname, Lastname FROM #SourceTable

  FETCH NEXT FROM SimpleCursor INTO @PersonID, @Firstname, @Lastname
  END

  CLOSE SimpleCursor
  DEALLOCATE SimpleCursor

SELECT * FROM #Destination

我在这里想念什么?虽然PersonID 102和103确实存在,但我没有更新任何内容。

非常感谢。

1 个答案:

答案 0 :(得分:0)

您没有使用在UPDATEINSERT语句中获取值的变量。试试:

...
IF EXISTS (SELECT *
                  FROM #Destination
                  WHERE PersonID = @PersonID)
BEGIN
  UPDATE #Destination
         SET FirstName = @FirstName,
             LastName = @LastName
         WHERE PersonID = @PersonID;
END
ELSE
BEGIN
  INSERT INTO #Destination
              (PersonID,
               FirstName,
               LastName)
              VALUES (@PersonID,
                      @FirstName,
                      @LastName);
END;
...