I am looking at this query and I am kinda confused by a few things.
-- T-SQL large update table
USE tempdb;
SELECT * INTO SOD
FROM AdventureWorks2008.Sales.SalesOrderDetail
GO
--(121317 row(s) affected)
-- SQL update in batches of 10,000
WHILE (2 > 1)
BEGIN
BEGIN TRANSACTION
UPDATE TOP ( 10000 ) SOD
SET UnitPriceDiscount = 0.08,
ModifiedDate = CONVERT(DATETIME,CONVERT(CHAR(10),getdate(),112))
WHERE ModifiedDate < CONVERT(DATETIME,CONVERT(CHAR(10),getdate(),112))
IF @@ROWCOUNT = 0
BEGIN
COMMIT TRANSACTION
BREAK
END
COMMIT TRANSACTION
-- 1 second delay
WAITFOR DELAY '00:00:01'
END -- WHILE
GO
/* Messages
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(10000 row(s) affected)
(1317 row(s) affected)
(0 row(s) affected)
*/
-- Cleanup
DROP TABLE SOD
GO
------------
- Is it making a temp table?
SELECT * INTO SODif so is this really needed? Can I just use the while part and below? - How does
IF @@ROWCOUNT = 0ever become zero? Does it do some self incrementing or something?
Edit
This is what I have now but I still think there is an endless loop or something
BEGIN TRAN
declare
@rows_updated int ,
@rowCount int,
@batch_size int
set @rows_updated = -1
set @batch_size = 10000
set @rowCount = 0;
Declare @xx VARCHAR(20) DECLARE @length INT
SET @length = 17 SET @xx = 'XXXXXXXXXXXXXXXX'
while ( @rows_updated != 0 )
begin
update top(@batch_size) myTbl
SET myNumber = SUBSTRING(@xx, 0, @length - len(RIGHT(myNumber, 4))) + RIGHT(myNumber, 4)
WHERE myDate <'2011-Jan-02'
set @rows_updated = @@rowcount
set @rowCount += 10000
print @rowCount
end
ROLLBACK
I did a count
select count(*) from myTbl
where myDate < '2011-Jan-02'
this brings back a count of 1,448,982
the last print out I got was 31,110,000
Edit 2
I added this and now it stops but it still is not 100% where it should be at
while (Select Count(*) From myTbl Where myDate <'2011-Jan-02' ) >= @rowCount
Edit 3
I think edit 2 is just doing the same 10,000 rows over and over again.
The provided script does the following:
Creates/Loads the permanent table SOD
while (true)
First, the
begin transactionandcommit transactionare unnecessary with a normal installation of SQL Server, unless you’ve explicitly changed theIMPLICIT_TRANSACTIONSsetting by executingSET IMPLICIT_TRANSACTIONS ON, in which case theBEGIN TRANSACTIONstatement is unecessary. The reason is the by default, SQL Servers runs in auto-commit mode, so every statement fires, sotto voce, acommiton success or arollbackon failure.Also, the logic is a little clunky. I’d write the loop like this:
which might make what’s going on a little more transparent.