从游标批量获取记录

时间:2016-07-26 08:31:45

标签: sql cursor batch-processing sql-server-2014

DECLARE table_cursor CURSOR LOCAL FAST_FORWARD READ_ONLY FOR 
     SELECT column5 
     FROM testdb.tableA

OPEN table_cursor;

FETCH NEXT FROM table_cursor INTO @m_column5

WHILE @@FETCH_STATUS = 0
BEGIN
    //two update queries are here
END

CLOSE table_cursor;
DEALLOCATE table_cursor;

让我们说这会返回1000万条记录。我可以在SQL Server 2014中批量获取结果吗?

我能采取更好的方法吗? (考虑到表现事实)

1 个答案:

答案 0 :(得分:0)

很难弄清楚您要使用该光标做什么。

基于您分享的所有内容,看来您真正想要做的是基于TOP子句的UPDATE:

UPDATE TOP (10) Sales.Store  
SET SalesPersonID = 276  
WHERE SalesPersonID = 275;

或需要联接的SELECT FROM UPDATE:

UPDATE [dbo].[Events]
SET [datetime]=SYSDATETIME()
FROM (SELECT TOP 1000 [id] FROM [dbo].[Events] WHERE [datetime]<CONVERT(DATE,SYSDATETIME()) [e2] 
INNER JOIN [dbo].[Events] ON [Events].[id] = [e2].[id];

如果您发现确实需要一个游标来支持您的过程,则可以继续:

WHILE EXISTS (SELECT 1 FROM [dbo].[Events] WHERE [datetime]<CONVERT(DATE,SYSDATETIME())
BEGIN
   -- Your logic here
END;