1. 我猜很多人第一选择是游标,但这个效率比较低下,少量数据还行,大量数据得等好长时间 比如 我们要删除一个企业信息,条件是 Password='longaq',有时候不仅仅是一张表,如下
[SQL] 纯文本查看 复制代码
declare @ComUserID int;
Declare Mycursor cursor for SELECT ComUserID FROM dbo.Com_Users WHERE Password='longaq'
Open Mycursor
Fetch next from Mycursor into @ComUserID --开始抓数据
while @@FETCH_STATUS = 0
begin
delete from Com_users where comUserID=@ComUserID
delete from Company where comUserID=@ComUserID
delete from Position where comUserID=@ComUserID
delete from Com_logo where comuserid=@ComUserID
Fetch next from Mycursor into @ComUserID
end
Close Mycursor --关闭游标
Deallocate Mycursor --删除游标
2.使用WHILE 循环
获取需处理表的所有行以及行号,取最小行号min和最大行号max,进行循环
[SQL] 纯文本查看 复制代码 DECLARE @intMinId INT,@intMaxId INT,@intClubID INT,@lngUpdateAmount BIGINT
SELECT RowID=IDENTITY(INT,1,1),A.ClubID,A.NeedAmount
INTO #templist
FROM Game.UserCreateClubDesk AS A WHERE A.ServerID=@intServerID
SELECT @intMinId =MIN(RowID),@intMaxId=MAX(RowID)
FROM #templist
WHILE @intMinId<=@intMaxId
BEGIN
SELECT @intClubID=ClubID,@lngUpdateAmount=NeedAmount
FROM #templist WHERE RowID=@intMinId
EXEC dbo.PrPsWeb_UpdateClubCash
@intClubID,
@sintSourceType,
@lngUpdateAmount,
'127.0.0.1',
@chvMemo,
NULL,
SET @intMinId=@intMinId+1
END
DROP TABLE #templist
3.还有一个for循环也有时候也能用到
利用游标循环更新MemberService表中的数据(更新每个用户所购买服务的时间)
[SQL] 纯文本查看 复制代码 DECLARE @UserId varchar(50)
DECLARE My_Cursor CURSOR --定义游标
FOR (SELECT UserId FROM dbo.MemberAccount) --查出需要的集合放到游标中
OPEN My_Cursor; --打开游标
FETCH NEXT FROM My_Cursor INTO @UserId; --读取第一行数据(将MemberAccount表中的UserId放到@UserId变量中)
WHILE @@FETCH_STATUS = 0 BEGIN PRINT @UserId; --打印数据(打印MemberAccount表中的UserId)
UPDATE dbo.MemberService SET ServiceTime = DATEADD(Month, 6, getdate()) WHERE UserId = @UserId; --更新数据
FETCH NEXT FROM My_Cursor INTO @UserId; --读取下一行数据(将MemberAccount表中的UserId放到@UserId变量中)
END CLOSE My_Cursor; --关闭游标
DEALLOCATE My_Cursor; --释放游标
GO
|