2009-08-29 15 views
5

¿Cómo usar C# para agregar una columna para una tabla de servidor sql?¿Cómo usar C# para agregar una columna para una tabla de servidor sql?

Por ejemplo, quiero ejecutar el siguiente código SQL en código C#:

alter table [Product] add 
[ProductId] int default 0 NOT NULL 
+1

La pregunta y la respuesta son demasiado obvias. Además, uno puede ejecutar dicha secuencia de comandos (agregar columna a una tabla) solo una vez. Sí, DDL es compatible con el espacio de nombres 'SqlClient'. –

+0

@AlexKudryashev: sí, un caso de RTM-iti va en ... – code4life

Respuesta

16

se debe utilizar un comando:


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(); 
    } 
} 
+1

DbCommand también implementa IDisposable, así que sugeriría poner eso en un bloque de uso también. – TrueWill

+1

Gracias. Pero el código anterior omitió el: command.Connection = connection; – Mike108

+0

@TrueWill, Mike108. Ustedes tienen razón +1 para los dos. –

2
SqlCommand cmd2 = new SqlCommand(); 
// create columns for healed 
cmd2 = new SqlCommand("ALTER TABLE TotalHeals ADD "+Healee+" INT", openCon); 
cmd2.ExecuteNonQuery(); 

Es curioso cómo SqlCommand es diferente entonces DbCommand

Cuestiones relacionadas