Using SQL Server and T-SQL, how can I update ALL tables tables with a specific name but different schemas under the same database?
:Update:
The updates include adding/deleting/modifying columns as well as changing specific values of rows.
I want to be able to deploy changes to a table across all schemas. Using the SQL Server Management Studio table designer, when I do a change and save, it allows me to save a script that can be used to deploy those changes to a different table. I want to be able to use that script on all tables with that specific name across all schemas.
:Update 2:
There reason for this request is that I want to ensure that updating a specific table across multiple schemas is easy to do. In the future, my application will undoubtedly change and if I see that it is difficult or inefficient to update schemas then I will opt to use something else.
Below is what I tried:
DECLARE @update_sql NVARCHAR(max)
DECLARE @table_name VARCHAR(45)
DECLARE c_tables CURSOR FOR
SELECT t.table_name
FROM INFORMATION_SCHEMA.TABLES t
WHERE t.table_name = 'TestTable'
AND t.table_catalog = 'MyDataBase'
OPEN c_tables
FETCH c_tables INTO @table_name
WHILE @@Fetch_Status = 0
BEGIN
SET @update_sql = N'ALTER TABLE '+@table_name+' ADD ColumnThree nvarchar(50) NULL'
EXEC sp_executesql @update_sql
END
CLOSE c_tables
DEALLOCATE c_tables
Running this generates the following error:
Cannot find the object "TestTable" because it does not exist or you do not have permissions.
The table exists and I'am running under dbo
which is the schema owner.
I also noticed the query takes sometime to run even with only 7 tables in the database and 3 schemas used on those tables. Would it be more efficient to just login with each schema's owner and run a generic script? Each schema owner would only have access to their respective schema and tables.