exec sp_executesql @sql 和 exec (@sql) SQL Server
来自 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
--或者
exec (@sql)
为什么 lobodava 选择 exec sp_executesql @sql
而不是 exec(@sql)
那么这里有什么区别?
在递归动态查询上使用 sp_executesql
是否更好?
在其他帖子中,他们说 sp_executesql 更有可能促进查询计划重用...... 那么它对此类查询有帮助吗?
A Dynamic SQL query from lobodava is:
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)
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为
EXEC sp_executesql
会缓存查询计划 -EXEC
不会。有关详细信息和很好的读物,请参阅:查询意味着查询的逻辑被暂时存储,并且可以使以后更快地运行查询。
Because
EXEC sp_executesql
will cache the query plan --EXEC
will not. For more info, and a very good read, see:Caching a query means that the logistics to the query are temporarily stored, and make running the query later on faster for it.