官术网_书友最值得收藏!

The sp_executesql procedure

The sp_executesql procedure is the recommended method for sending an ad hoc T-SQL statement to SQL Server. If stored procedures cannot be leveraged for some reason, such as when T-SQL statements must be constructed dynamically by the application, sp_executesql allows the user to send an ad hoc T-SQL statement as a parameterized query, which uses a similar caching mechanism to stored procedures. This ensures that the plan can be reused whenever the same query is executed again. Building on our example from the Ad hoc plan caching section, we can rewrite the query using sp_executesql, as in the following example which can be executed in the AdventureWorks sample database:

EXECUTE sp_executesql @stmt = N'SELECT LastName, FirstName, MiddleName
FROM Person.Person
WHERE PersonType = @PersonType;'
, @params = N'@PersonType nchar(2)'
, @PersonType = N'EM';

This ensures that any time the same query is sent with the same parameter markers, the plan will be reused, even if the statement is dynamically generated by the application.

主站蜘蛛池模板: 伊金霍洛旗| 靖边县| 海门市| 揭东县| 东山县| 伊宁市| 余庆县| 儋州市| 邢台县| 绿春县| 怀化市| 太白县| 宜昌市| 海原县| 新丰县| 平谷区| 博爱县| 定西市| 岳西县| 理塘县| 青龙| 达拉特旗| 胶州市| 自治县| 九江县| 孟津县| 平昌县| 资中县| 田东县| 饶平县| 双流县| 门头沟区| 曲松县| 衡阳市| 吉安县| 南皮县| 贵南县| 金秀| 广南县| 固安县| 东兰县|