exec sp_executesql @sql 和 exec (@sql) SQL Server

发布于 2024-10-21 01:39:24 字数 1208 浏览 2 评论 0原文

来自 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

帝王念 2024-10-28 01:39:24

因为 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文