很多数据管理员DBA会告诉你尽量避免使用cursor. 它会锁住读取的数据甚至表单。经过搜索和研究,觉得用以下方法作为替代最好。代码是我用模板(Template)的形式写的。将代码粘贴到SQL Server Management Studio (SSMS), 按住Ctl + Shilft + M, 然后点击OK, 就可以运行了。
-- ============================================= -- Use while loop to avoid cursor -- ============================================= DECLARE@NumberRecordsint, @RowCountint DECLARE@ProductIDint, @ProductNamenvarchar(200) DECLARE<@table_variable, sysname, @tbl_loop>asTABLE ( RowID intidentity(1,1), ProductID int, ProductName nvarchar(200) ) INSERT<@table_variable, sysname, @tbl_loop> (ProductID, ProductName) <select_statement, , SELECTTOP10 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
3. SQL2000 中的旧模板,被放在"Earlier Versions" 文件夹下. 例如游标cursor的模板就在这里
4. 你可以创建自己的文件夹和模板
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>