Timur Lenk

Timur Lenk

  • NA
  • 18
  • 3.5k

c# sql column name

Oct 1 2015 4:40 PM
Hi,
 
I hope someone can help me.
 
I working on a visual studio project. I would like add a new column to my existing sql table (tbl_names). The column name is a string (newCol).
 
I tried two different ways: 
 

con.Open();

SqlCommand inc = new SqlCommand("ALTER TABLE tbl_names ADD " + newCol + " varchar(3)", con);

inc.ExecuteNonQuery();

con.Close();

 
And:
 

con.Open();

var incString = string.Format("ALTER TABLE tbl_names ADD " + newCol + " varchar(3)");

SqlCommand inc = new SqlCommand(incString, con);

con.Close();

 
Unfortunately I got errors when I tried them.
 
How can I add a new column if the column's name is a string?
 
I am new to c# so help would be great. 
 
 
Thanks,
 
Timur 
 

Answers (5)