views:

371

answers:

1

How to use C# to add a column for a table of sql server?

For example, I want to execute the following sql in C# code:

alter table [Product] add 
[ProductId] int default 0 NOT NULL
+5  A: 

You should use a Command:


using (DbConnection connection = new SqlConnection("Your connection string")) {
    connection.Open();
    using (DbCommand command = new SqlCommand("alter table [Product] add [ProductId] int default 0 NOT NULL")) {
        command.Connection = connection;
        command.ExecuteNonQuery();
    }
}
Alfred Myers
DbCommand also implements IDisposable, so I'd suggest putting that in a using block as well.
TrueWill
Thank you. But the above code missed the:command.Connection = connection;
Mike108
@TrueWill, Mike108. You guys are right. +1 for both of you.
Alfred Myers