問題描述
我只是在閱讀我公司的代碼指南,它說永遠不要將變量視為 sql server 中的常量,而是使用文字.原因是當你在查詢中使用變量時,sql server 無法建立一個好的執行計劃.
I'm just reading my company's code guidelines and it says to never treat variables as a constant in sql server, use literals instead. The reasoning is that sql server can't build a good execution plan when you're using variables in the query.
有人知道這是否仍然正確嗎?我們使用的是 MSSQL 2005,此文檔可能是為 2000 年編寫的.
Anybody know if this is still true? We're using MSSQL 2005 and this document may have been written for 2000.
推薦答案
這對于 SQL Server 2005 來說通常"是正確的,因為它現在嘗試為盡可能多的查詢預先生成執行計劃.您的里程可能會有所不同,因為它取決于您的數據和您的 SARG(測試您的查詢計劃并查看),但此 tecdoc(他們使用的是 SQL Server 2005 的預發布版本)指出:
This is "generally" true for SQL Server 2005 since it now tries to pre-generate execution plans for as many queries as possible. Your mileage may vary since it depends on your data and your SARG (test your query plans and see) but this tecdoc (they were using a pre-release version of SQL Server 2005) states:
http://www.microsoft.com/technet/prodtechnol/sql/2005/qrystats.mspx
避免使用局部變量查詢
如果在查詢中使用局部變量謂詞而不是參數或字面上,優化器求助于降低質量的估計或猜測謂詞的選擇性.用查詢中的參數或文字而不是局部變量,并且優化器通常能夠選擇一個更好的查詢計劃.例如,考慮這個使用本地的查詢變量:
If you use a local variable in a query predicate instead of a parameter or literal, the optimizer resorts to a reduced-quality estimate, or a guess for selectivity of the predicate. Use parameters or literals in the query instead of local variables, and the optimizer typically will be able to pick a better query plan. For example, consider this query that uses a local variable:
這篇關于TSQL 常量...使用變量還是文字?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!