Altering all tables in the database

So today I was doing some thinking about my next project, and I decided that I should not be deleting records willy nilly and instead using a flag for deletion.  I know, I’m a little behind the times, this is certainly basic database management, but you know how things are.  We do what we do because we learned our bad habits from programmers before us.  The bigger picture is, experience and reading peer materials (best practices blogs and websites) teach us how to think differently, and how to correct some of our bad habits.  As one who is always interested in correcting those bad habits, I came across a nifty solution.

Using the mysql Show Tables syntax in a ColdFusion cfquery, I am able to pull down a query result set of all of the tables within the database that I am working on.  Using that query is very simple then to loop over and conduct a new query that alters the tables, adding on the new column that I wanted.

<CFQUERY NAME=”test” datasource=”#dsn#” username=”#dbuser#” password=”#dbpass#”>    
  show tables;
</CFQUERY>

The query will output with a column named TABLES_IN_xxxxx where xxxxx is the name of your database.   Using this as my new variable, I can loop over the results and use the alter table to add my little ‘deleted’ switch.

<cfoutput query=”test”>
 <CFQUERY NAME=”testUpd” datasource=”#dsn#” username=”#dbuser#” password=”#dbpass#”>    
  ALTER TABLE #test.tables_in_xxxxx#
  ADD Deleted TINYINT(1) UNSIGNED NOT NULL DEFAULT 0;
 </CFQUERY>
</cfoutput>

So there you have it.  A nice tidy way to make a mass update to all tables in the database.  This can be modified in all sorts of ways.  Say I wanted to change the datatype of one of my fields, and it has foreign key references all over the place.  Well, I can do the same thing with the CHANGE column syntax.  Of course, as always, be wary of housing this online anywhere where it could be accessible to those who would have some ill intent, having database permission to alter tables is a dangerous set of permissions to be floating around.