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

[亡魂溺海] 提交于 2019-12-21 08:59:39

问题


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?


回答1:


Because EXEC sp_executesql will cache the query plan -- EXEC will not. For more info, and a very good read, see:

  • The Curse and Blessings of Dynamic SQL

Caching a query means that the logistics to the query are temporarily stored, and make running the query later on faster for it.



来源:https://stackoverflow.com/questions/5255463/exec-sp-executesql-sql-and-exec-sql-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!