公司使用SQL Server数据库存储有关其客户及其业务交易的信息。为您所在的城市引入了新的区号。前缀小于500的电话号码的区域代码111保持不变。前缀大于等于500的电话号码将被分配为222的区域代码。“客户”表中“电话”列中的所有电话号码都存储为char(12)字符串,其格式为``999-999-9999’‘。我必须对“客户”表进行适当的更改
使用最少的管理工作来尽快。我应该使用哪一个?
a.
UPDATE Customers SET Phone = ‘222-‘ + SUBSTRING(Phone,5,8) FROM Customers WHERE SUBSTRING(Phone,1,3) = ‘111’ AND SUBSTRING(Phone,5,3) >= 500
b.
DECLARE PhoneCursor CURSOR FOR SELECT Phone FROM Customers WHERE SUBSTRING(Phone,1,3) = 111 AND SUBSTRING(Phone,5,3) >= 500 OPEN PhoneCursor FETCH NEXT FROM PhoneCursor WHILE @@FETCH_STATUS = 0 BEGIN UPDATE Customers SET Phone = ‘222’ + SUBSTRING(Phone,5,8) WHERE CURRENT OF PhoneCursor FETCH NEXT FROM PhoneCursor END CLOSE PhoneCursor DEALLOCATE PhoneCursor
较大的更新将使数据库事务长时间保持下去……将事情锁定并造成各种破坏。
为此,我建议使用游标将负载分散一段时间。
我还做了一个“分块”更新…像这样:
DECLARE @Done bit = 0 WHILE @Done = 0 BEGIN UPDATE TOP(10000) Customers SET Phone = ‘222-‘ + SUBSTRING(Phone,5,8) FROM Customers WHERE SUBSTRING(Phone,1,3) = ‘111’ AND SUBSTRING(Phone,5,3) >= 500 IF @@ROWCOUNT = 0 BEGIN SET @Done = 1 END END