方法一:使用游标(此方法适用所有情况,对标结构没有特殊要求。)

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使用游标或临时表遍历数据的更多相关文章

  1. 转:SQL SERVER数据库中实现快速的数据提取和数据分页

    探讨如何在有着1000万条数据的MS SQL SERVER数据库中实现快速的数据提取和数据分页.以下代码说明了我们实例中数据库的“红头文件”一表的部分数据结构: CREATE TABLE [dbo]. ...

  2. SQL Server 表变量和临时表的区别

    SQL Server 表变量和临时表的区别 一.表变量 表变量在SQL Server 2000中首次被引入.表变量的具体定义包括列定义,列名,数据类型和约束.而在表变量中可以使用的约束包括主键约束,唯 ...

  3. SQL Server 中 with tmp 临时表的用法

    SQL Server 中 with tmp 临时表的用法 ----------with临时表用法,有时候采用临时表比采用in的效率更高,避免了全表扫描. 实例中实现了查询普通题.大题.子题目的sql ...

  4. SQL Server服务器上需要导入Excel数据的必要条件

    SQL Server服务器上需要导入Excel数据,必须安装2007 Office system 驱动程序:数据连接组件,或者Access2010的数据库引擎可再发行程序包,这样就不必在服务器上装Ex ...

  5. SQL Server ---(CDC)监控表数据(转译)

    一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 实现过程(Realization) 补充说明(Addon) 参考文献(References) ...

  6. SQL Server使用convert对datetime日期数据进行获取

    来源:http://database.51cto.com/art/201007/211883.htm 备注:本文的语法讲解确实是比较乱,似乎格式不太严谨.参考时还是以实例验证为准比较好 以下的文章主要 ...

  7. 将Excel导入SQL Server 只能导入数字,其他数据变为NULL怎么解决?

    先新建一个TXT文件,把数据粘贴进去 再新建一个Excel文件,在菜单栏中选Data再选From Text 找到txt文件,点import 一定要选Text 点Finish,点OK. 接下来在往数据库 ...

  8. SQL Server 2008中新增的变更数据捕获(CDC)和更改跟踪

    来源:http://www.cnblogs.com/downmoon/archive/2012/04/10/2439462.html  本文主要介绍SQL Server中记录数据变更的四个方法:触发器 ...

  9. SQL Server 之 在数据库之间进行数据导入导出

    1.同一服务器上数据库之间进行数据导入导出 (1).使用 SELECT INTO 导出数据 在SQL Server中使用最广泛的就是通过SELECT INTO语句导出数据,SELECT INTO语句同 ...

随机推荐

  1. ubuntu下eclipse scala开发插件(Scala IDE for Eclipse)安装

    1. 环境介绍 系统:ubuntu16.04(不过和系统版本关系不大) elipse:Neon.1aRelease (4.6.1) 2. 插件介绍 Scala IDE for eclipse是elip ...

  2. ELK Kafka json to elk

    Logstash配置     input { kafka { zk_connect => "127.0.0.1:2181" topic_id => "clus ...

  3. HashMap和HashSet

    Java使用Set接口来描述集合,而Set中每一个数据元素都是唯一的. HashSet散列集合 Hash算法:把任意长度输入,通过散列算法,变换成固定长度的输出即散列值.对不同类型信息,散列值公式也是 ...

  4. js对已经对象类型进行类型辨别

    typeof() Object.prototype.toString.call(data)

  5. 理解 OpenStack + Ceph (1):Ceph + OpenStack 集群部署和配置

    本系列文章会深入研究 Ceph 以及 Ceph 和 OpenStack 的集成: (1)安装和部署 (2)Ceph RBD 接口和工具 (3)Ceph 物理和逻辑结构 (4)Ceph 的基础数据结构 ...

  6. Docker on Microsoft Azure

    Docker蓬勃发展,如日中天.微软自然也不甘落后,且不说即将发布的.支持Docker技术的Windows Nano Server和Windows Server 2016.我们来看看在Microsof ...

  7. plain framework 1 参考手册 入门指引之 简明教程

    简明教程 简单的例子 实现代码 简单的例子 如果你已经下载好整个框架的源码,那么你可以在这里找到应用的例子: plainframework/applications/pf_simple 如果你在win ...

  8. 彻底解决mysql中文乱码的办法,修改mysql解压缩版(免安装版或zip版)字符编码

    MySQL会出现中文乱码的原因不外乎下列几点:1.server本身设定问题,例如server字符编码还停留在latin12.table的语系设定问题(包含character与collation)3.客 ...

  9. (二)工厂方法模式-C++实现

    工厂方法模式:定义一个用于创建对象的借口,让子类决定实例化哪一个类. Factory method使一个类的实例化延迟到子类. 当系统准备为用户提供某个类的子类的实例,又不想让用户代码和孩子类形成耦合 ...

  10. reflect2015破解

    具体看 http://download.congci.com/download/net-reflector-7-6-1-824-wanquan-pojie#downloads *博主注:因为很多破解程 ...