很多数据管理员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
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>
相关链接:
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
本文介绍了一种在SQL Server中使用while循环代替Cursor的方法,以减少数据锁定的问题。通过声明变量和临时表,利用身份字段进行记录迭代,实现了高效的数据处理。
65

被折叠的 条评论
为什么被折叠?



