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

时间:2011-03-10 04:29:38

标签: sql sql-server tsql sql-server-2008 dynamic-sql

来自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)

为什么lobodava选择exec sp_executesql @sql而不是exec(@sql) 那么这有什么不同呢? 使用sp_executesql on recursive dynamic queries更好吗? 在其他帖子中,他们说sp_executesql更有可能促进查询计划重用... 那么它有助于这些类型的查询吗?

1 个答案:

答案 0 :(得分:12)

由于EXEC sp_executesql会缓存查询计划,因此EXEC不会。有关更多信息和非常好的阅读,请参阅:

缓存查询意味着临时存储查询的后勤,并使以后更快地运行查询。