구현 된 현재 솔루션은 끔찍합니다!ADO.Net DataTable을 SQL 테이블에 삽입하십시오.
가 나는 SQL 테이블에 대한 ADO.NET 데이터 테이블에서 레코드를 삽입하기위한 for... loop
를 사용합니다.
나는
는 가능 ... 반복하지 않고 SQL 테이블에 데이터 테이블 한 번에 삽입 할, 또는 내가 너무 많은 요구는 무엇입니까?구현 된 현재 솔루션은 끔찍합니다!ADO.Net DataTable을 SQL 테이블에 삽입하십시오.
가 나는 SQL 테이블에 대한 ADO.NET 데이터 테이블에서 레코드를 삽입하기위한 for... loop
를 사용합니다.
나는
는 가능 ... 반복하지 않고 SQL 테이블에 데이터 테이블 한 번에 삽입 할, 또는 내가 너무 많은 요구는 무엇입니까?나는 당신이 SQLBulkCopy 찾고있는 생각합니다.
당신은 하나의 테이블 반환 매개 변수로 전체의 DataTable을 통과 한 번에 전체 TVP를 삽입 할 수 있습니다. 다음은 Table-Valued Parameters in SQL Server 2008 (ADO.NET)에서 예입니다
// Assumes connection is an open SqlConnection.
using (connection)
{
// Create a DataTable with the modified rows.
DataTable addedCategories = CategoriesDataTable.GetChanges(
DataRowState.Added);
// Define the INSERT-SELECT statement.
string sqlInsert =
"INSERT INTO dbo.Categories (CategoryID, CategoryName)"
+ " SELECT nc.CategoryID, nc.CategoryName"
+ " FROM @tvpNewCategories AS nc;"
// Configure the command and parameter.
SqlCommand insertCommand = new SqlCommand(
sqlInsert, connection);
SqlParameter tvpParam = insertCommand.Parameters.AddWithValue(
"@tvpNewCategories", addedCategories);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.CategoryTableType";
// Execute the command.
insertCommand.ExecuteNonQuery();
}
TVP는 SQL 2008
당신은 또한 다음과 같은 방법을 시도 할 수 있습니다에서만 사용할 수 있습니다.
private void button1_Click(object sender, EventArgs e)
{
tabevent();
DataSet ds = new DataSet();
DataTable table = new DataTable("DataFromDGV");
ds.Tables.Add(table);
foreach (DataGridViewColumn col in dataGridView1.Columns)
table.Columns.Add(col.HeaderText, typeof(string));
foreach (DataGridViewRow row in dataGridView1.Rows)
{
table.Rows.Add(row);
foreach (DataGridViewCell cell in row.Cells)
{
table.Rows[row.Index][cell.ColumnIndex] = cell.Value;
}
}
// DataTable ds1changes = ds1.Tables[0].GetChanges();
if (table != null)
{
SqlConnection dbConn = new SqlConnection(@"Data Source=wsswe;Initial Catalog=vb;User ID=sa;Password=12345");
SqlCommand dbCommand = new SqlCommand();
dbCommand.Connection = dbConn;
foreach (DataRow row in table.Rows)
{
if (row["quantity"] != null && row["amount"]!=null && row["itemname"]!=null)
{
if (row["amount"].ToString() != string.Empty)
{
dbCommand.CommandText =
"INSERT INTO Bill" +
"(Itemname,Participants,rate,Quantity,Amount)" +
"SELECT '" + Convert.ToString(row["itemname"]) + "' AS Itemname,'" + Convert.ToString(row["Partcipants"]) + "' AS Participants,'" + Convert.ToInt32(row["rate"]) + "' AS rate,'" +
Convert.ToInt32(row["quantity"]) + "' AS Quantity,'" + Convert.ToInt32(row["amount"]) + "' AS Amount";
dbCommand.Connection.Open();
dbCommand.ExecuteNonQuery();
if (dbCommand.Connection.State != ConnectionState.Closed)
{
dbCommand.Connection.Close();
}
MessageBox.Show("inserted");
}
}
}
}
}
dataAdapter를 사용하면 자체적으로 처리합니다. – garik