SQL Server使用游标或临时表遍历数据
方法一:使用游标(此方法适用所有情况,对标结构没有特殊要求。)
declare @ProductName nvarchar()
declare pcurr cursor for select ProductName from Products
open pcurr
fetch next from pcurr into @ProductName
while (@@fetch_status = )
begin
print (@ProductName)
fetch next from pcurr into @ProductName
end
close pcurr
deallocate pcurr
--给空的sort进行赋值 从1开始按顺序排
declare @id int declare cursor1 cursor for
select ClassId from [content] group by ClassId
open cursor1
fetch next from cursor1 into @id
while @@fetch_status=0
begin
select ROW_NUMBER()over(order by id) as pid,id into #ttttt from [content] where classid=@id;
update [content] set sort = pid from #ttttt where #ttttt.id = [content].id;
drop table #ttttt;
fetch next from cursor1 into @id
end close cursor1
在关系数据库中,我们对于查询的思考是面向集合的。而游标打破了这一规则,游标使得我们思考方式变为逐行进行.
对于游标一些优化建议
- 如果能不用游标,尽量不要使用游标
- 用完用完之后一定要关闭和释放
- 尽量不要在大量数据上定义游标
- 尽量不要使用游标上更新数据
- 尽量不要使用insensitive, static和keyset这些参数定义游标
- 如果可以,尽量使用FAST_FORWARD关键字定义游标
- 如果只对数据进行读取,当读取时只用到FETCH NEXT选项,则最好使用FORWARD_ONLY参数
- 参考:http://www.cnblogs.com/moss_tan_jun/archive/2011/11/26/2263988.html
方法二:使用循环(此方法适用于表带有自动增加标识的字段)
declare @ProductName nvarchar()
declare @ProductID int
select @ProductID=min(ProductID) from Products
while @ProductID is not null
begin
select @ProductName=ProductName from Products where
ProductID=@ProductID
print(@ProductName);
select @ProductID=min(ProductID) from Products where
ProductID>@ProductID
end
--删除临时表#Tmp
create table #Tmp --创建临时表#Tmp
(
ID int IDENTITY (,) not null, --创建列ID,并且每次新增一条记录就会加1
WokNo varchar(),
primary key (ID) --定义ID为临时表#Tmp的主键
); --declare @temp table
--(
-- [id] int IDENTITY(,),
-- [Name] varchar()
--) Select * from #Tmp --查询临时表的数据
truncate table #Tmp --清空临时表的所有数据和约束
相关例子:
Declare @Wokno Varchar() --用来记录职工号
Declare @Str NVarchar() --用来存放查询语句
Declare @Count int --求出总记录数
Declare @i int
Set @i =
Select @Count = Count(Distinct(Wokno)) from #Tmp
While @i < @Count
Begin
Set @Str = 'Select top 1 @Wokno = WokNo from #Tmp Where id not in (Select top ' + Str(@i) + 'id from #Tmp)'
Exec Sp_ExecuteSql @Str,N'@WokNo Varchar(500) OutPut',@WokNo Output
Select @WokNo,@i --一行一行把职工号显示出来
Set @i = @i +
End --drop table #temp
USE Test_DBData;
GO
--修正表中REC_CreateBy,REC_ModifyBy
CREATE TABLE #temp
(
id INT IDENTITY(, ) ,
tablename NVARCHAR()
);
DECLARE @tablename NVARCHAR();
DECLARE @n INT;
DECLARE @count INT;
DECLARE @str NVARCHAR();
--用来存放查询语句
DECLARE @tableCreateBy NVARCHAR();
DECLARE @tableModifyBy NVARCHAR();
SELECT @n = ;
INSERT #temp
( tablename
)
SELECT name
FROM sysobjects
WHERE type = 'U '
AND (name <> 'Dim_Employee')
AND (name <> 'Fct_ChannelType')
AND (name <> 'Rel_TPOCommodityMessage')
AND (name LIKE 'Dim%' OR name LIKE 'Fct%' OR name LIKE 'Rel%');
SELECT @count = @@rowcount;
WHILE @n <= @count
BEGIN
SELECT @tablename = ( SELECT tablename
FROM #temp
WHERE id = @n
);
SET @tableCreateBy = @tablename + '.REC_CreateBy';
SET @tableModifyBy = @tablename + '.REC_ModifyBy';
SET @str = 'IF EXISTS ( SELECT *
FROM ( SELECT '+@tableCreateBy+'
FROM '+@tablename+'
INNER JOIN dbo.Dim_Employee ON '+@tableCreateBy+' = Dim_Employee.LoginName
) tb)
BEGIN
UPDATE '+@tablename+'
SET REC_CreateBy = Dim_Employee.EmployeeId
FROM '+@tablename+'
INNER JOIN dbo.Dim_Employee ON '+@tableCreateBy+' = Dim_Employee.LoginName;
END;
IF EXISTS ( SELECT *
FROM ( SELECT '+@tableModifyBy+'
FROM '+@tablename+'
INNER JOIN dbo.Dim_Employee ON '+@tableModifyBy+' = Dim_Employee.LoginName
) tb )
BEGIN
UPDATE '+@tablename+'
SET REC_ModifyBy = Dim_Employee.EmployeeId
FROM '+@tablename+'
INNER JOIN dbo.Dim_Employee ON '+@tableModifyBy+' = Dim_Employee.LoginName;
END;
';
EXEC(@str);
SELECT @n = @n + ;
DELETE FROM #temp
WHERE tablename = @tablename;
END;
--删除临时表
IF OBJECT_ID(N'tempdb.dbo.#temp') IS NOT NULL
BEGIN
DROP TABLE #temp;
END
.分批更新数据库
declare @x int
set @x=
while(@x<=)
begin
begin tran
update UserFavorite set UserFavorite.firstpublishtime = product.lastpublishtime
from UserFavorite,product where UserFavorite.productid = product.id
and UserFavorite.id between (@x-)* and @x*
commit tran
set @x=@x+
WAITFOR DELAY '00:00:30'; --等待5秒
end
SQL Server使用游标或临时表遍历数据的更多相关文章
- 转:SQL SERVER数据库中实现快速的数据提取和数据分页
探讨如何在有着1000万条数据的MS SQL SERVER数据库中实现快速的数据提取和数据分页.以下代码说明了我们实例中数据库的“红头文件”一表的部分数据结构: CREATE TABLE [dbo]. ...
- SQL Server 表变量和临时表的区别
SQL Server 表变量和临时表的区别 一.表变量 表变量在SQL Server 2000中首次被引入.表变量的具体定义包括列定义,列名,数据类型和约束.而在表变量中可以使用的约束包括主键约束,唯 ...
- SQL Server 中 with tmp 临时表的用法
SQL Server 中 with tmp 临时表的用法 ----------with临时表用法,有时候采用临时表比采用in的效率更高,避免了全表扫描. 实例中实现了查询普通题.大题.子题目的sql ...
- SQL Server服务器上需要导入Excel数据的必要条件
SQL Server服务器上需要导入Excel数据,必须安装2007 Office system 驱动程序:数据连接组件,或者Access2010的数据库引擎可再发行程序包,这样就不必在服务器上装Ex ...
- SQL Server ---(CDC)监控表数据(转译)
一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 实现过程(Realization) 补充说明(Addon) 参考文献(References) ...
- SQL Server使用convert对datetime日期数据进行获取
来源:http://database.51cto.com/art/201007/211883.htm 备注:本文的语法讲解确实是比较乱,似乎格式不太严谨.参考时还是以实例验证为准比较好 以下的文章主要 ...
- 将Excel导入SQL Server 只能导入数字,其他数据变为NULL怎么解决?
先新建一个TXT文件,把数据粘贴进去 再新建一个Excel文件,在菜单栏中选Data再选From Text 找到txt文件,点import 一定要选Text 点Finish,点OK. 接下来在往数据库 ...
- SQL Server 2008中新增的变更数据捕获(CDC)和更改跟踪
来源:http://www.cnblogs.com/downmoon/archive/2012/04/10/2439462.html 本文主要介绍SQL Server中记录数据变更的四个方法:触发器 ...
- SQL Server 之 在数据库之间进行数据导入导出
1.同一服务器上数据库之间进行数据导入导出 (1).使用 SELECT INTO 导出数据 在SQL Server中使用最广泛的就是通过SELECT INTO语句导出数据,SELECT INTO语句同 ...
随机推荐
- 重新认识mapreduce
写这篇文章,是因为最近遇到了mapreduce的二次排序问题.以前的理解不完全正确.首先看一下mapreduce的过程 相信这张图熟悉MR的人都应该见过,再来一张图 wordcount也不细说了,ha ...
- Storm系列(三):创建Maven项目打包提交wordcount到Storm集群
在上一篇博客中,我们通过Storm.Net.Adapter创建了一个使用Csharp编写的Storm Topology - wordcount.本文将介绍如何编写Java端的程序以及如何发布到测试的S ...
- ZooKeeper日志与快照文件简单分析
有用过Zookeeper的都知道zoo.cfg配置文件中有dataDir配置项用于存储数据,不过可能有些人不太清楚这个目录具体存储的是那些数据,默认情况下这个目录是用于存储Log(事务日志)与Snap ...
- 32-bit Assembly on x86_64 Linux (Use Nasm and ld&gcc)
Assembly on x86_64 Linux Some instructions in Intel assembly set are invalid in x86_64 env. e.g. aaa ...
- Java开发之@PostConstruct和@PreConstruct注解
从Java EE5规范开始,Servlet增加了两个影响Servlet生命周期的注解(Annotation):@PostConstruct和@PreConstruct.这两个注解被用来修饰一个非静态的 ...
- 《Python核心编程》部分代码习题实践(持续更新)
第三章 3-10 交换异常处理方式 代码: #makeTextFile.py #!/usr/bin/env python 'makeTextFile.py' import os ls = os.lin ...
- ADO.Net 增、删、改、查(基本项)
数据访问 对应命名空间:System.Data.SqlClient; SqlConnection:连接对象 SqlCommand:命令对象 SqlDataReader:读取器对象 CommandTex ...
- div根据内容改变大小并且左右居中
div{ display:inline-block; width:auto; } 这个div的父元素text-align:center;
- I/O工作机制
I/O问题是任何编程语言都无法回避的问题,可以说I/O是整个人机交互的核心问题,因为I/O是机器获取和交换信息的主要渠道.java的I/O操作类在包java.io下,大概有将近80个类,这些类大概可以 ...
- 代码管理工具之git的学习
1.代码管理工具git的学习 http://www.ruanyifeng.com/blog/2015/12/git-cheat-sheet.html 2.github的使用帮助 https:// ...