How to write a cursor inside a stored procedure in SQL Server 2008

前端 未结 3 1133
栀梦
栀梦 2021-02-20 06:28

I have two tables in my database

Coupon Table

  • id (int)
  • Name (nvarchar(max))
  • NoofUses (int)

Coup

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-20 06:46

    Try the following snippet. You can call the the below stored procedure from your application, so that NoOfUses in the coupon table will be updated.

    CREATE PROCEDURE [dbo].[sp_UpdateCouponCount]
    AS
    
    Declare     @couponCount int,
                @CouponName nvarchar(50),
                @couponIdFromQuery int
    
    
    Declare curP cursor For
    
      select COUNT(*) as totalcount , Name as name,couponuse.couponid  as couponid from Coupon as coupon 
      join CouponUse as couponuse on coupon.id = couponuse.couponid
      where couponuse.id=@cuponId
      group by couponuse.couponid , coupon.Name
    
    OPEN curP 
    Fetch Next From curP Into @couponCount, @CouponName,@couponIdFromQuery
    
    While @@Fetch_Status = 0 Begin
    
        print @couponCount
        print @CouponName
    
        update Coupon SET NoofUses=@couponCount
        where couponuse.id=@couponIdFromQuery
    
    
    Fetch Next From curP Into @couponCount, @CouponName,@couponIdFromQuery
    
    End -- End of Fetch
    
    Close curP
    Deallocate curP
    

    Hope this helps!

提交回复
热议问题