Add new column to database table programmatically

Let’s see how we can add a new column to an existing table in database using c#.

SqlConnection Connection = null;
 
try
{
	Connection = new SqlConnection(
	"Data Source=" + sql_server_ip_or_hostname + ";" +
	"Initial Catalog=" + database_name + ";" +
	"User Id=" + username + ";" +
	"Password=" + password + ";" +
	"Connect Timeout=30;"));
	Connection.Open();
}
catch
{
	Connection = null;
}
 
if(Connection != null) {
    SqlCommand Command = Connection.CreateCommand();
    Command.CommandText = "ALTER TABLE my_table_name ADD column_name INT;";
    Command.ExecuteNonQuery();
    Command = null;
    Connection.Close();
    Connection = null;
}

With the same c# code you can also drop a column, rename it or even change its data type!
enjoy!

%d bloggers like this: