Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Loop through all tables in DB and add column

Status
Not open for further replies.

ErrolDC2

MIS
Apr 6, 2005
43
0
0
US
Could someone share a simple exmaple with me?

Thanks,

 
Yes. All the tables in this database are identical. I need to add 2 columns to the tables to upgrade them for higher revision of the application that is using the database.
 
[!]** I strongly encourage you to make a good backup of the database before doing this.[/!]

Code:
sp_msforeachtable 'Alter Table ? Add [!]NewColumn Int[/!]'

You will need to modify the above statement to accommodate your column name and data type. If the column already exists, you will get an error message like this...

[tt][red]Column names in each table must be unique. Column name 'NewColumn' in table 'dbo.testData' is specified more than once.[/red][/tt]

So, if the column already exists, it will not be added, but the statement will continue on to the next table.

-George

"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top