A Dynamic SQL query from lobodava is:
lobodava的动态SQL查询是:
declare @sql nvarchar(4000) =
N';with cteColumnts (ORDINAL_POSITION, COLUMN_NAME) as
(
select ORDINAL_POSITION, COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = N'''+ @tableName + ''' and COLUMN_NAME like ''' + @columnLikeFilter + '''
),
cteValues (ColumnName, SumValue) as
(
SELECT ColumnName, SumValue
FROM
(SELECT ' + @sumColumns + '
FROM dbo.' + @tableName + ') p
UNPIVOT
(SumValue FOR ColumnName IN
(' + @columns + ')
)AS unpvt
)
select row_number() over(order by ORDINAL_POSITION) as ID, ColumnName, SumValue
from cteColumnts c inner join cteValues v on COLUMN_NAME = ColumnName
order by ORDINAL_POSITION'
exec sp_executesql @sql
--OR
exec (@sql)
exec sp_executesql @sql --OR exec(@sql)
Why did lobodava pick exec sp_executesql @sql
and not exec(@sql)
So what is the difference here?
Is it better to use sp_executesql on recursive dynamic queries
?
In other post they say sp_executesql
is more likely to promote query plan reuse... So it helps in these kind of queries?
为什么lobodava选择exec sp_executesql @sql而不是exec(@sql)那么这里有什么区别?在递归动态查询中使用sp_executesql更好吗?在其他帖子中,他们说sp_executesql更有可能促进查询计划重用...所以它有助于这些类型的查询?
1 个解决方案
#1
12
Because EXEC sp_executesql
will cache the query plan -- EXEC
will not. For more info, and a very good read, see:
因为EXEC sp_executesql将缓存查询计划 - EXEC不会。有关更多信息和非常好的阅读,请参阅:
- The Curse and Blessings of Dynamic SQL
- 动态SQL的诅咒与祝福
Caching a query means that the logistics to the query are temporarily stored, and make running the query later on faster for it.
缓存查询意味着临时存储查询的后勤,并使以后更快地运行查询。
#1
12
Because EXEC sp_executesql
will cache the query plan -- EXEC
will not. For more info, and a very good read, see:
因为EXEC sp_executesql将缓存查询计划 - EXEC不会。有关更多信息和非常好的阅读,请参阅:
- The Curse and Blessings of Dynamic SQL
- 动态SQL的诅咒与祝福
Caching a query means that the logistics to the query are temporarily stored, and make running the query later on faster for it.
缓存查询意味着临时存储查询的后勤,并使以后更快地运行查询。