I want to update the column Last_Modified
in every table in a given schema. This column is updated with latest timestamp if another column in the same table (ENDTIME
) is updated.
To do this I have the following script in SQL Server:
DECLARE @TotalRows FLOAT
SET @TotalRows = (SELECT COUNT(*) FROM table1)
DECLARE @TotalLoopCount INT
SET @TotalLoopCount = CEILING(@TotalRows / 100000)
DECLARE @InitialLoopCount INT
SET @InitialLoopCount = 1
DECLARE @AffectedRows INT
SET @AffectedRows = 0
DECLARE @intialrows INT;
SET @intialrows = 1
DECLARE @lastrows INT
SET @lastrows = 100000;
WHILE @InitialLoopCount <= @TotalLoopCount
BEGIN
WITH updateRows AS
(
SELECT
t1.*,
ROW_NUMBER() OVER (ORDER BY caster) AS seqnum
FROM
table1 t1
)
UPDATE updateRows
SET last_modified = ENDTIME AT TIME ZONE 'Central Standard Time'
WHERE last_modified IS NULL
AND updateRows.ENDTIME IS NOT NULL
AND updateRows.seqnum BETWEEN @intialrows AND @lastrows;
SET @AffectedRows = @AffectedRows + @@ROWCOUNT
SET @intialrows = @intialrows + 100000
SET @lastrows = @lastrows + 100000
-- COMMIT
SET @Remaining = @TotalRows - @AffectedRows
SET @InitialLoopCount = @InitialLoopCount + 1
END
This script determines the count of a table, divides it by 100000 and runs only that many loops to perform the entire update. It breaks down the update in batches/loops and then perform updates on certain rows until it completes updating them all.
This script is only for 1 table, i.e table1. I want to now modify this script in such a way that it dynamically takes all the tables in a schema and runs the above script for each of them. Let's say the schema name is schema1 and it has 32 tables, so this script should run for all those 32 tables.
I am able to retrieve the tables in schema1 but I am not able to dynamically send those to this script. Can anyone please help me with this?