如何在 SQL Server 2008 中的存储过程中编写游标

How to write a cursor inside a stored procedure in SQL Server 2008(如何在 SQL Server 2008 中的存储过程中编写游标)
本文介绍了如何在 SQL Server 2008 中的存储过程中编写游标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我的数据库中有两个表

优惠券表

  • id (int)
  • 名称 (nvarchar(max))
  • NoofUses (int)

优惠券使用表

  • id(int)
  • 优惠券(int)
  • 创建日期(日期时间)

每当用户点击优惠券时,都会有一个条目进入包含该优惠券 ID 的 CouponUse

Whenever a user clicks on a coupon an entry goes into the CouponUse table containing that Coupon's id

现在在 coupon 表中有一个名为 NoofUses 的列.我想在存储过程中编写一个游标,该过程循环 couponuse 表并查看一张优惠券有多少行,并在优惠券的 NoofUses 字段中填写该数字.

Now there is a column in the coupon table called NoofUses. I want to write a cursor inside a stored procedure which loops over couponuse table and sees how many rows are there for one coupon and fill that number in NoofUses field in coupon.

我有这个查询

  select COUNT(*) as totalcount , Name as name from Coupon as coupon 
  join CouponUse as couponuse on coupon.id = couponuse.couponid
  group by couponuse.couponid , coupon.Name

它给了我优惠券名称和 couponuse 的计数

which gives me the coupon name and its count from couponuse

但我不知道如何在使用游标的存储过程中实现它?

But I don't know how to implement that in a stored procedure using a cursor ?

您提出的任何问题都将不胜感激,谢谢

Anything you ask about question will be appreciated , Thanks

推荐答案

仅仅使用一个简单的 UPDATE 语句有什么问题??

What's wrong with just simply using a single, simple UPDATE statement??

UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)

这就是所需要的!没有凌乱复杂的游标,没有循环,没有 RBAR(逐行痛苦)处理......只是一个漂亮、简单、干净的基于集合的 SQL 语句.

That's all that's needed ! No messy and complicated cursor, no looping, no RBAR (row-by-agonizing-row) processing ..... just a nice, simple, clean set-based SQL statement.

这篇关于如何在 SQL Server 2008 中的存储过程中编写游标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)