using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.Globalization; namespace ServerExplorer.UI { public partial class FrmExec : Form { private string cnxString; public FrmExec(string cnxString) { InitializeComponent(); this.cnxString = cnxString; } private void frmExec_Load(object sender, EventArgs e) { } private DataTable Exec() { SqlConnection cnx; DataTable dt; SqlDataAdapter da; // Establecer conexion cnx = new SqlConnection(cnxString); // Obtener resultado en un datatable. da = new SqlDataAdapter(txtCommand.Text, cnx); dt = new DataTable(); cnx.Open(); da.Fill(dt); cnx.Close(); return dt; } private void btnExec_Click(object sender, EventArgs e) { try { // Ejecutar consulta DataTable dt = Exec(); // Mostrar resultados dgvDatos.DataSource = dt; } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnGenInserts_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); DataTable ddt; string destname = String.Empty; NumberFormatInfo nfi = new NumberFormatInfo(); // Preparar un conversor de formato numerico que use puntos para los decimales nfi.NumberDecimalSeparator = "."; // Obtener el nombre de la tabla destino destname = Microsoft.VisualBasic.Interaction.InputBox("Nombre de la tabla destino", "tabla destino", String.Empty, this.Top + (this.Height / 2), this.Left + (this.Width / 2)); try { // Ejecutar consulta dt = Exec(); } catch (Exception ex) { MessageBox.Show(ex.Message); } // Preparar la datatable destino ddt = new DataTable(); ddt.Columns.Add("Comando", typeof(String)); // Recorrer la tabla de datos foreach (DataRow dr in dt.Rows) { string strColumns = String.Empty; string strValues = String.Empty; foreach (DataColumn dc in dt.Columns) { // El nombre de la columna if (strColumns != String.Empty) strColumns += ", "; strColumns += "[" + dc.ColumnName + "]"; // El valor de la columna if (strValues != String.Empty) strValues += ", "; object valor = dr[dc]; if (valor == DBNull.Value) { // NULOS strValues += "NULL"; } else if (dc.DataType.Name.ToLower() == "string") { // Cadenas strValues += "'" + ((string)valor).Replace("'", "''") + "'"; } else if (dc.DataType.Name.ToLower() == "decimal") { // Decimales strValues += ((decimal)valor).ToString(nfi); } else { // Otros strValues += valor.ToString(); } } // Insertar fila a la datatable destino ddt.Rows.Add(new object[] { "INSERT INTO " + destname + " (" + strColumns + ") "+ "VALUES (" + strValues + ")" }); } // Establecer el resultado dgvDatos.DataSource = ddt; } private void dgvDatos_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.DesiredType == typeof(Image)) { if (e.Value is DBNull || (e.Value is byte[] && ((byte[])e.Value).Length <= 0)) { e.Value = new Bitmap(1, 1); } } } } }