表格变量在游标循环内

时间:2016-01-15 05:55:07

标签: sql-server tsql

我注意到当我在游标循环中声明一个表变量时,该变量会持续游标生命周期。我的问题是,如果有办法以这样的方式声明变量,它的生命周期只会持续到迭代?这是一个样本:

DECLARE @SourceTable TABLE(Id INT IDENTITY(1,1),Remarks VARCHAR(10))
INSERT INTO @SourceTable VALUES ('First')
INSERT INTO @SourceTable VALUES ('Second')
INSERT INTO @SourceTable VALUES ('Third ')

/* declare variables */
DECLARE @variable INT

DECLARE my_cursor CURSOR FAST_FORWARD READ_ONLY FOR SELECT Id FROM @SourceTable

OPEN my_cursor

FETCH NEXT FROM my_cursor INTO @variable

WHILE @@FETCH_STATUS = 0
BEGIN
    --Dose not creates a new instance
    DECLARE @VarTable TABLE (Remarks VARCHAR(10))

    INSERT INTO @VarTable
    SELECT TOP 1 Remarks FROM @SourceTable
    WHERE Id = @variable


    --Works as intended if you drop when done
    CREATE TABLE #TempTable  (Remarks VARCHAR(10))

    INSERT INTO #TempTable
    SELECT TOP 1 Remarks FROM @SourceTable
    WHERE Id = @variable

    DROP TABLE #TempTable

    FETCH NEXT FROM my_cursor INTO @variable
END

CLOSE my_cursor
DEALLOCATE my_cursor

SELECT * FROM @VarTable

但它变得更加令人困惑。如果您尝试查询光标外的临时表,则会出现错误。看起来好像临时表是这种情况的唯一正确方法吗?

1 个答案:

答案 0 :(得分:4)

TSQL变量的范围是从它的声明到批处理结束。

因此在内部游标中,每个循环都需要从table variable

中删除数据

我知道奇怪的是,在游标中的每个循环表变量都被声明但是它是如何工作的

在外部声明表变量并在CURSOR

中执行插入/删除语句
DECLARE @VarTable TABLE (Remarks VARCHAR(10))

DECLARE my_cursor CURSOR FAST_FORWARD READ_ONLY FOR SELECT Id FROM @SourceTable

OPEN my_cursor
.......
.......
  DROP TABLE #TempTable

  DELETE FROM @VarTable

  FETCH NEXT FROM my_cursor INTO @variable
END
....