Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 469
edgarmtze Avatar asked Feb 02 '23 20:02

edgarmtze


1 Answers

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.

like image 169
OMG Ponies Avatar answered Feb 05 '23 16:02

OMG Ponies