且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在存储过程中编写游标

更新时间:2022-12-12 13:10:02

你好,

我不认为你需要使用光标。游标太慢了。你永远不应该使用游标。



这是一个UPDATE命令可以解决你的问题:



Hello,
I don''t think that you need to use a cursor. The cursors are too slow. You should never use cursors.

Here is an UPDATE command which resolves your problem:

UPDATE [Coupon table] SET NoofUses = Total.Nr
FROM [Coupon table] INNER JOIN 
         (SELECT COUNT(Couponid) AS Nr, Couponid FROM [CouponUse Table] GROUP BY Couponid)Total
ON Total.Couponid = [Coupon table].id


当Sandeep消化时。网上有很多这方面的例子。但是,使用游标,它们可能会很慢。它们有很多用途,但大多数实例可以使用普通外观,基于集合的查询或使用RANK / DENSE_RANK函数进行排序,以便您可以根据查询插入/更新。



试着看看你是否可以在没有游标的情况下完成这项任务。如果需要游标,则使用此格式。还要注意光标的额外开关(FAST_FORWARD,READONLY等)



SQL游标:



http://msdn.microsoft.com/en-GB/library/ms180169.aspx [ ^ ]



As Sandeep sugested. There are many examples on the web for this. however, with cursors they can be slow. There are many uses for them but the majority of instances you can use normal looks, set based queries or use RANK / DENSE_RANK functions for ordering so that you can insert / update based on query.

Try to see if you can accomplish this without a cursor. If a cursor is needed then use this format. Also note the extra switches for the cursor (FAST_FORWARD, READONLY etc)

SQL Cursors:

http://msdn.microsoft.com/en-GB/library/ms180169.aspx[^]

DECLARE @Col1 INT,
        @Col2 VARCHAR(100)

DECLARE cur CURSOR FAST_FORWARD FOR 
SELECT col1, col2
FROM TableName

OPEN cur

FETCH NEXT FROM cur 
INTO @Col1, @Col2

WHILE @@FETCH_STATUS = 0
BEGIN
    --Write your insert / update statement here based on @col variables.


    FETCH NEXT FROM cur
    INTO @Col1, @Col2
END 
CLOSE cur;
DEALLOCATE cur;





如果有,请告诉我其他什么?



Let me know if there is anything else?


class sss
{



}