You're absolutely right! Using three separate cursors is inefficient. Here's a much better approach with a single cursor that handles all three tables in one pass:
DECLARE @TableName VARCHAR(50);
DECLARE @ID INT;
DECLARE @RandomValue INT;
-- Create a temporary table to hold all records to update
CREATE TABLE #RecordsToUpdate (
TableName VARCHAR(50),
ID INT
);
-- Populate with records from all three tables
INSERT INTO #RecordsToUpdate (TableName, ID)
SELECT 'Table1', ID FROM Table1 WHERE SomeCondition = 1
UNION ALL
SELECT 'Table2', ID FROM Table2 WHERE SomeCondition = 1
UNION ALL
SELECT 'Table3', ID FROM Table3 WHERE SomeCondition = 1;
-- Declare and open cursor
DECLARE UpdateCursor CURSOR FOR
SELECT TableName, ID FROM #RecordsToUpdate;
OPEN UpdateCursor;
FETCH NEXT FROM UpdateCursor INTO @TableName, @ID;
WHILE @@FETCH_STATUS = 0
BEGIN
-- Get random value from unrelated table
SELECT TOP 1 @RandomValue = RandomField
FROM UnrelatedTable
ORDER BY NEWID();
-- Dynamic SQL to update the appropriate table
DECLARE @SQL NVARCHAR(MAX);
SET @SQL = N'UPDATE ' + QUOTENAME(@TableName) +
N' SET FieldToUpdate = @RandomValue WHERE ID = @ID';
EXEC sp_executesql @SQL,
N'@RandomValue INT, @ID INT',
@RandomValue = @RandomValue,
@ID = @ID;
FETCH NEXT FROM UpdateCursor INTO @TableName, @ID;
END
-- Clean up
CLOSE UpdateCursor;
DEALLOCATE UpdateCursor;
DROP TABLE #RecordsToUpdate;
Key Improvements:
- Single Cursor: Processes all records from all three tables in one pass
- Dynamic SQL: Uses
sp_executesql to safely execute the update against the correct table
- Temporary Table: Stores all records to be updated in one place
- Efficiency: Much better performance than three separate cursors
Alternative Without Dynamic SQL:
If you prefer to avoid dynamic SQL, you can use a CASE statement approach:
DECLARE @ID INT;
DECLARE @RandomValue INT;
DECLARE @TableIndicator INT; -- 1=Table1, 2=Table2, 3=Table3
-- Create a temporary table with all records
CREATE TABLE #AllRecords (
TableIndicator INT,
ID INT
);
INSERT INTO #AllRecords (TableIndicator, ID)
SELECT 1, ID FROM Table1 WHERE SomeCondition = 1
UNION ALL
SELECT 2, ID FROM Table2 WHERE SomeCondition = 1
UNION ALL
SELECT 3, ID FROM Table3 WHERE SomeCondition = 1;
DECLARE UpdateCursor CURSOR FOR
SELECT TableIndicator, ID FROM #AllRecords;
OPEN UpdateCursor;
FETCH NEXT FROM UpdateCursor INTO @TableIndicator, @ID;
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT TOP 1 @RandomValue = RandomField
FROM UnrelatedTable
ORDER BY NEWID();
-- Update the appropriate table based on the indicator
IF @TableIndicator = 1
UPDATE Table1 SET FieldToUpdate = @RandomValue WHERE ID = @ID;
ELSE IF @TableIndicator = 2
UPDATE Table2 SET FieldToUpdate = @RandomValue WHERE ID = @ID;
ELSE IF @TableIndicator = 3
UPDATE Table3 SET FieldToUpdate = @RandomValue WHERE ID = @ID;
FETCH NEXT FROM UpdateCursor INTO @TableIndicator, @ID;
END
CLOSE UpdateCursor;
DEALLOCATE UpdateCursor;
DROP TABLE #AllRecords;