I created a simple table and inserted one thousand rows of data, but it took 10 seconds to insert only 1000 rows. Is this a normal insertion speed? It seems unusually slow. What could be the cause of this issue?
Create Table
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DB](
[CODE] [varchar](20) NOT NULL,
[DATE] [datetime2](7) NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[DB] ADD CONSTRAINT [DF_DB_DATE] DEFAULT (getdate()) FOR [DATE]
GO
Insert Data
private void button1_Click(object sender, EventArgs e)
{
for (int i = 1000; i < 2000; i++)
{
string query = $"INSERT INTO dbo.DB(CODE) VALUES('CHOCO{i}')";
SqlExecuteNonQuery(query);
}
}
private bool SqlExecuteNonQuery(string query)
{
try
{
if (conn.State == ConnectionState.Closed)
conn.Open();
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
return false;
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
return true;
}
3条答案
按热度按时间nzk0hqpo1#
It's normal to be slow as you are inserting rows one by one. It will be better to pass the data to SQL Server stored procedure like XML, JSON or CSV like format. Then parse this data and put it in temporary table, perform some validations if needed and then insert the data at once:
qf9go6mv2#
Did you try rebuild-index?
If you have more data then use bulk insert for better performance.
Regards,
xlpyo6sf3#
At first I thought your problem was that you were opening your connection for each of the rows.
Than I did a simple Test Program but it looks like you are right, it takes around 10s =(. Edit: I remade my tests on a machine on the same network as the SQL Server Machine, the results were much better (more bellow)
Also, you should parametrize your query. ;)
The results were (in ms)
A) Using the same network
| # | EachTime | SameConnection | BulkCopy | MultipleValues |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| 1 | 1182 | 489 | 252 | 39 |
| 2 | 891 | 503 | 13 | 44 |
| 3 | 876 | 497 | 13 | 34 |
| 4 | 870 | 629 | 13 | 44 |
| 5 | 879 | 549 | 12 | 37 |
| 6 | 888 | 604 | 12 | 43 |
| 7 | 890 | 561 | 18 | 40 |
| 8 | 889 | 518 | 12 | 35 |
| 9 | 868 | 534 | 12 | 34 |
| 10 | 868 | 541 | 18 | 34 |
| -------- | -------------- | -------------- | -------------- | -------------- |
| Average | 910 | 543 | 38 | 38 |
B) Over the Internet