運行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.