相关疑难解决方法(0)

使用 SqlCommand.Prepare() 的意义和好处是什么?

我遇到了开发人员代码,其中 SqlCommand.Prepare() (参见 MSDN)方法在执行 SQL 查询之前被广泛使用。我想知道这样做有什么好处?

样本:

command.Prepare();
command.ExecuteNonQuery();
//...
command.Parameters[0].Value = 20;
command.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)

我玩了一点并进行了追踪。调用Prepare()方法后执行Command,使Sql Server执行如下语句:

declare @p1 int
set @p1=1
exec sp_prepexec @p1 output,N'@id int,@desc text',N'INSERT INTO dbo.testtable (id) VALUES (@id)',@id=20'
select @p1
Run Code Online (Sandbox Code Playgroud)

之后,当 Parameter 获取它的值并被SqlCommand.ExecuteNonQuery()调用时,将在 Sql-Server 上执行以下操作:

exec sp_execute 1,@id=20
Run Code Online (Sandbox Code Playgroud)

对我来说,这看起来就像语句在Prepare()执行时被编译。我想知道这样做有什么好处?这是否意味着它被放入计划缓存中,并且可以在使用所需参数值执行最终查询后立即重新使用?

我发现(并在另一个问题中记录了它)使用 SqlParameters 执行的 SqlCommands 总是包含在sp_executesql过程调用中。这使得 Sql Server 能够独立于参数值存储和重用计划。

关于这一点,我想知道该prepare()方法是无用的还是过时的,或者我在这里遗漏了什么?

sql-server execution-plan sql-server-2008-r2 prepared-statement plan-cache

16
推荐指数
2
解决办法
5350
查看次数