游标


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

使用游标的最好方式是不用游标。
why cursor is slow,It acquires locks which table variable does not do, and that is why Cursor is slow.

游标替代方案:

--Declare variables
DECLARE @item_category_id INT
Declare @X BIGINT
Set @X = 0
--Declare a memory table
DECLARE @item_table TABLE (item_category_id INT)

INSERT INTO @item_table(item_category_id)
SELECT  object_id
From master.sys.objects c1(NOLOCK)

--WHILE @loop_counter > 0 AND @item_category_counter <= @loop_counter
WHILE (SELECT COUNT(1) FROM @item_table) > 0
BEGIN
    SELECT TOP 1 @item_category_id = item_category_id
    FROM @item_table 
    
    --处理
    Set @X = @X + @item_category_id
    
   delete from @item_table where item_category_id = @item_category_id
END
PRINT @X