January 02, 2010

Quickly Add and Drop a Column from all Tables in SQL Server




If you have been looking out for a quick way to add and drop a column from all the tables in SQL Server, then here’s the query for it. I will use an undocumented stored procedure sp_MSforeachtable for this purpose

USE Northwind
GO
-- Add a Column to all tables
EXEC sp_MSforeachtable 'ALTER TABLE ? ADD ColumnTemp varchar(10) NULL'

-- Remove a Column from all tables
EXEC sp_MSforeachtable 'ALTER TABLE ? DROP COLUMN ColumnTemp'

The query shown above adds the column ‘ColumnTemp’ to all tables in the Northwind database. Similar the ‘ColumnTemp’ is then removed from all the tables.

Note: While removing a column, I am assuming there are no constraints defined.


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

1 Response to "Quickly Add and Drop a Column from all Tables in SQL Server"
  1. Madhivanan said...
    February 3, 2010 at 6:40 AM

    Note that sp_msforeachtable is undocumented and can be removed in future realeases. So better simulate it as shown here

    http://beyondrelational.com/blogs/madhivanan/archive/2008/05/13/simulating-undocumented-procedures.aspx

    Madhivanan

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions