5
Answers

c# sql column name

Ask a question
Timur Lenk

Timur Lenk

9y
577
1
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)