运行SQL Server 2005上查询的两个版本时,我们看到了奇怪的现象:需要与SQL Server上的SQL查询帮助2005
版本答:
SELECT otherattributes.* FROM listcontacts JOIN otherattributes
ON listcontacts.contactId = otherattributes.contactId WHERE listcontacts.listid = 1234
ORDER BY name ASC
版本B:
DECLARE @Id AS INT;
SET @Id = 1234;
SELECT otherattributes.* FROM listcontacts JOIN otherattributes
ON listcontacts.contactId = otherattributes.contactId
WHERE listcontacts.listid = @Id
ORDER BY name ASC
这两个查询都返回1000行;版本A平均需要15秒;版本B平均需要4s。 任何人都可以帮助我们理解这两个SQL版本的执行时间差异吗?
如果我们调用使用NHibernate通过命名参数此查询,我们看到通过SQL Server事件探查以下查询:
EXEC sp_executesql N'SELECT otherattributes.* FROM listcontacts JOIN otherattributes ON listcontacts.contactId = otherattributes.contactId WHERE listcontacts.listid = @id ORDER BY name ASC',
N'@id INT',
@id=1234;
...这往往是表现不佳的版本A.