[SQL模板] 避免使用游标 cursor 的最佳方法

本文介绍了一种在SQL Server中使用while循环代替Cursor的方法,以减少数据锁定的问题。通过声明变量和临时表,利用身份字段进行记录迭代,实现了高效的数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


很多数据管理员DBA会告诉你尽量避免使用cursor. 它会锁住读取的数据甚至表单。经过搜索和研究,觉得用以下方法作为替代最好。代码是我用模板(Template)的形式写的。将代码粘贴到SQL Server Management Studio (SSMS), 按住Ctl + Shilft + M, 然后点击OK, 就可以运行了。

--  =============================================
--
 Use while loop to avoid cursor
--
 =============================================

DECLARE   @NumberRecords   int @RowCount   int
DECLARE   @ProductID   int @ProductName   nvarchar ( 200 )

DECLARE   < @table_variable , sysname,  @tbl_loop >   as   TABLE  (
    RowID 
int   identity ( 1 , 1 ),
    ProductID 
int ,
    ProductName 
nvarchar ( 200 )
)

INSERT   < @table_variable , sysname,  @tbl_loop >  (ProductID, ProductName)
< select_statement, ,  SELECT   TOP   10  ProductID, ProductName  FROM  Northwind.dbo.Products >

--  Get the number of records in the table variable
SET   @NumberRecords   =   @@ROWCOUNT
SET   @RowCount   =   1


WHILE   @RowCount   <=   @NumberRecords
BEGIN

    
SELECT   @ProductID   =  ProductID,  @ProductName   =  ProductName
    
FROM   < @table_variable , sysname,  @tbl_loop >
    
WHERE  RowID  =   @RowCount

    
--  Insert your code here
     PRINT   '  Product Name:  '   +   @ProductName

    
SET   @RowCount   =   @RowCount   +   1
END

SQL2005 Template - 模板的制作和使用方法

1. 打开模板浏览器 Ctl + Alt + T
2. 你可以看到很多自代的模板,例如用SQL发Email
mail
3. SQL2000 中的旧模板,被放在"Earlier Versions" 文件夹下. 例如游标cursor的模板就在这里
  old

4. 你可以创建自己的文件夹和模板

         create

5. 也可以将模板文件直接放到以下路径, 然后关闭再打开SSMS,就可以看到新加的模板了

Window XP:
C:/Documents and Settings/<user>/Application Data/Microsoft/Microsoft SQL Server/90/Tools/Shell/Templates/Sql/<some folder>. 
Windows Vista:
C:/Users/<user>/AppData/Roaming/Microsoft/Microsoft SQL Server/90/Tools/Shell/Templates/Sql/<some folder>

相关链接
1. 如何使用Table Variable, Local/Global Temporary Table, and Permanent Table  (极力推荐!)
http://databases.aspfaq.com/database/should-i-use-a-temp-table-or-a-table-variable.html
http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1267047,00.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值