September 22, 2011 at 3:18 am
Please help me to write a query on database for adding one column to all the tables present in that database?
September 22, 2011 at 3:25 am
Looks like home work question.
select 'Alter table ' + s.name + '.' + T.name +' Add Name varchar(5)' from sys.tables T Inner join sys.schemas S
on T.schema_id = S.schema_id
September 22, 2011 at 4:26 am
Undocumented and unsupported, but should work.
EXEC sp_msForEachTable 'ALTER TABLE [?] ADD newColumn int NULL'
-- Gianluca Sartori
September 22, 2011 at 7:56 am
Or a cursor over sys.all_objects to filter tables and execute EXEC 'ALTER TABLE ' + @youTable + ' ADD...'
-
Lic. Andrés M. Aiello
DBA MSSQL - Oracle
http://aiellodba.blogspot.com/
@AndresAiello
September 23, 2011 at 9:15 am
Slight variation on a previous response that doesn't require the join, and uses QUOTENAME to ensure validity of the table/schema name:
SELECT
'ALTER TABLE ' +
QUOTENAME(SCHEMA_NAME(schema_id)) + '.' +
QUOTENAME(name) + ' ADD Name VARCHAR(5);'
FROM
sys.tables
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply