How to write a query on database to add one column to all the tables in that database?

  • Please help me to write a query on database for adding one column to all the tables present in that database?

  • 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

  • Undocumented and unsupported, but should work.

    EXEC sp_msForEachTable 'ALTER TABLE [?] ADD newColumn int NULL'

    -- Gianluca Sartori

  • 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

  • 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