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.
About The Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of
DotNetCurry,
DNC Magazine for Developers,
SQLServerCurry and
DevCurry. He has also authored a couple of books
51 Recipes using jQuery with ASP.NET Controls and a new one recently at
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.
Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook
1 comment:
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
Post a Comment