以下查询运行缓慢。对于memberid中的一个值,memberid0,memberid1 ........ memberid9中有多个条目。因此,每个语句都会影响多行更新。当然,表格大小以MB为单位
Declare @memberName nvarchar(250)
Declare @memberID bigint
Declare @dimId int
Declare @levelId int
Declare @newName nvarchar(250)
Declare @updateSQL1 nvarchar(500)
Declare @updateSQL2 nvarchar(500)
Declare @cursorStmt nvarchar(300)
Declare @custCounter bigint
Declare @prodCounter bigint
Declare @regCounter bigint
Declare @memberCounter int
SET @custCounter = 1
SET @prodCounter = 1
SET @regCounter = 1
SET @memberCounter = 0
BEGIN TRANSACTION
While @memberCounter < 3
Begin
Set @cursorStmt = 'Declare memberCursor CURSOR
FOR Select name, memberid, dimensionId, levelNumber from member' + CAST(@memberCounter as NVARCHAR(1)) + ' where memberID <> 0 order by memberid'
print @cursorStmt
exec sp_executesql @cursorStmt
OPEN memberCursor
FETCH NEXT FROM memberCursor INTO @memberName, @memberId, @dimId, @levelId
WHILE @@FETCH_STATUS = 0
BEGIN
IF @dimId = 0
BEGIN
SET @newName = 'Customer_' + CAST(@custCounter AS NVARCHAR(10)) + '_LEVEL_' + CAST(@levelId AS NVARCHAR(10))
SET @custCounter = @custCounter + 1
END
else if @dimId = 1
BEGIN
SET @newName = 'Product_' + CAST(@prodCounter AS NVARCHAR(10)) + '_LEVEL_' + CAST(@levelId AS NVARCHAR(10))
SET @prodCounter = @prodCounter + 1
END
else if @dimId = 2
BEGIN
SET @newName = 'Region_' + CAST(@regCounter AS NVARCHAR(10)) + '_LEVEL_' + CAST(@levelId AS NVARCHAR(10))
SET @regCounter = @regCounter + 1
END
SET @updateSQL1 = 'Update Member' + CAST(@dimId AS NVARCHAR(5)) + ' set name = ''' + @newName + ''' where memberId = ' + CAST(@memberId AS NVARCHAR(10))
SET @updateSQL2 = 'Update Member' + CAST(@dimId AS NVARCHAR(5)) + ' set memberName' + CAST(@levelId-1 AS NVARCHAR(5)) + ' = ''' + @newName + ''' where memberId' + CAST(@levelId-1 AS NVARCHAR(5)) + ' = ' + CAST(@memberId AS NVARCHAR(10))
--print @updateSQL1
--print @updateSQL2
exec sp_executesql @updateSQL1
exec sp_executesql @updateSQL2
FETCH NEXT FROM memberCursor INTO @memberName, @memberId, @dimId, @levelId
END
CLOSE memberCursor
DEALLOCATE memberCursor
Set @memberCounter = @memberCounter + 1
END
答案 0 :(得分:0)
我双重marc_s说,但如果你不想那样做, 尝试创建一个包含Update语句的表,然后在每个查询的一批最少10个更新中执行它们。
尝试创建两个表以存储两种不同类型的更新,因此在批处理中,您只能进行至少10行的更新。我想在一次查询中尽可能多地更新。
单个SQL查询中的多个更新速度更快,请参阅: Why are batch inserts/updates faster? How do batch updates work?