ExecuteNonQuery 删除近7000条记录耗时较多,如何提高性能?
ExecuteNonQuery Takes more time to delete nearly 7000 records, How can I improve performance?
我正在使用 ADO.NET 执行以下查询。执行需要将近60s。同时我在SQL Server management studio 运行查询时,只用了1秒。为什么会有如此大的差异?我该如何提高性能?
我也尝试了存储过程。它也需要将近 60 秒。
SqlCommand sc = new SqlCommand(@"
BEGIN TRAN
BEGIN TRY
DELETE FROM [dbo].[Table1]
WHERE ID = @Id ; -- nearly 600 records
DELETE FROM [dbo].[Table2]
WHERE ID = @Id ; -- nearly 6500 records
DELETE FROM [dbo].[Table3]
WHERE ID = @Id; -- 1 record
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
THROW
END CATCH
");
我在下面试过了。这是由于参数嗅探而发生的。为了克服这个问题,有4种方法
- 选项(重新编译)
- 选项(优化(@VARIABLE=VALUE))
- 选项(优化(@VARIABLE UNKNOWN))
- 使用局部变量
下面我使用了第四种方法来解决这个问题。 referred
SqlCommand sc = new SqlCommand(@"
BEGIN TRAN
BEGIN TRY
Declare @Id int = @PId ; -- passing the parameter only here
DELETE FROM [dbo].[Table1]
WHERE ID = @Id ; -- nearly 600 records
DELETE FROM [dbo].[Table2]
WHERE ID = @Id ; -- nearly 6500 records
DELETE FROM [dbo].[Table3]
WHERE ID = @Id; -- 1 record
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
THROW
END CATCH
");
感谢大家做出更好的回答
我正在使用 ADO.NET 执行以下查询。执行需要将近60s。同时我在SQL Server management studio 运行查询时,只用了1秒。为什么会有如此大的差异?我该如何提高性能?
我也尝试了存储过程。它也需要将近 60 秒。
SqlCommand sc = new SqlCommand(@"
BEGIN TRAN
BEGIN TRY
DELETE FROM [dbo].[Table1]
WHERE ID = @Id ; -- nearly 600 records
DELETE FROM [dbo].[Table2]
WHERE ID = @Id ; -- nearly 6500 records
DELETE FROM [dbo].[Table3]
WHERE ID = @Id; -- 1 record
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
THROW
END CATCH
");
我在下面试过了。这是由于参数嗅探而发生的。为了克服这个问题,有4种方法
- 选项(重新编译)
- 选项(优化(@VARIABLE=VALUE))
- 选项(优化(@VARIABLE UNKNOWN))
- 使用局部变量
下面我使用了第四种方法来解决这个问题。 referred
SqlCommand sc = new SqlCommand(@"
BEGIN TRAN
BEGIN TRY
Declare @Id int = @PId ; -- passing the parameter only here
DELETE FROM [dbo].[Table1]
WHERE ID = @Id ; -- nearly 600 records
DELETE FROM [dbo].[Table2]
WHERE ID = @Id ; -- nearly 6500 records
DELETE FROM [dbo].[Table3]
WHERE ID = @Id; -- 1 record
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
THROW
END CATCH
");
感谢大家做出更好的回答