exec sp_executesql @sql and exec (@sql) SQL Server
Asked Answered
U

1

9

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?

Unpromising answered 10/3, 2011 at 4:29 Comment(0)
S
12

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.

Sideling answered 10/3, 2011 at 4:41 Comment(2)
So, it is good to use,sp_executesql on this kind of query because of query plan, right?Unpromising
@darkcminor: Yes, EXEC sp_executesql should be what you use in the majority of cases, when you have to use dynamic SQL on SQL Server.Sideling

© 2022 - 2024 — McMap. All rights reserved.