Alter an Existing Database Table
Submitted by Date of submission User level
Mahesh Chand Dec 01, 2000 Beginner
There are some occasions when you need to change your database schema at runtime (from your program). Some of these changes are pretty simple such as create a new table but some of them are not easy. I was dealing with same kind of changes lately. These changes include
Adding a new column to an existing table
Deleting a column from a table
Changing type of a column
Changing constraints of a column
ALTER TABLE SQL statement helps us to solve these problems. You can execute a direct SQL query on a database by using CDaoDatabase or CDatabase MFC classes. Here I have taken CDaoDatabase class to do so. Here are the steps:
Open a database
I have an access database and it is stored in a CString szKCDB ;. My database has a table called 'myTable' which has a field 'myField' of long type.
CString sql;
CDaoDatabase* myDB;
myDB = new CDaoDatabase();
try
{
if ( !myDB->IsOpen() )
myDB->Open(szKCDB, FALSE,FALSE,_T(""));
}
Create a SQL Query
Adding a new column to an existing table
sql = "ALTER TABLE myTable ADD newColumn VARCHAR(255) " ;
Deleting a column
sql = "ALTER TABLE myTable DROP COLUMN myCloumn" ;
Changing Data type of a column
sql = "ALTER TABLE myTable ADD myColumn VARCHAR(255) " ;
Adding new constraints to a column
sql = "ALTER TABLE myTable ADD Recordkey COUNTER CONSTRAINT MyConst1 PRIMARY KEY" ;
Run the SQL Query
myDB->Execute(sql);
Did you like this article? Please send your feedback to the Author. Your feedback helps us to improve the quality of our next article. If you have any questions, please post on discussion forums.
About the Author:
Mahesh is Admin and the founder of this site. He has been programming in VC++, Visual Basic, COM, ATL, Database Programming for 4 years. He can be reached at Mahesh. His background includes Master's in Computer Science and Applications and Batchelor's in Mathematics and Physics.