I am trying to find all tables that have a certain column and then search that column for a given value and replace it.
My Query looks like this:
DECLARE @TableName NVARCHAR(255)
DECLARE @Sql NVARCHAR(MAX)
-- Iterate through each table
DECLARE table_cursor CURSOR FOR
SELECT t.name
FROM sys.tables t
JOIN sys.columns c ON t.object_id = c.object_id
WHERE c.name = 'CHAMBERID'
OPEN table_cursor
FETCH NEXT FROM table_cursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Sql = N'UPDATE ' + QUOTENAME(@TableName) +
N' SET CHAMBERID = REPLACE(CHAMBERID, ''1'', ''9'')'
EXEC sp_executesql @Sql
FETCH NEXT FROM table_cursor INTO @TableName
END
CLOSE table_cursor
DEALLOCATE table_cursor
When I run the query, I get the following error message
Msg 208, Level 16, State 1, Line 1
Invalid object name 'CI_AAA_HARDWARE'.
When I select that table and look at the data, the column exists and the search string exists. I do not understand why it fails.
Does anybody have an idea where I am going wrong?
Thank you all 🙂
Alex