Search code examples
sql-servert-sql

How to set value to variable using 'execute' in t-sql?


DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId int 
exec ('SELECT TOP 1 @siteId = Id FROM ' + @dbName + '..myTbl')  
select @siteId

When I run the script above I get the following error

Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "@siteId".

(1 row(s) affected)

Why and how to fix it?

Thank you


Solution

  • You can use output parameters with sp_executesql.

    DECLARE @dbName nvarchar(128) = 'myDb'
    DECLARE @siteId int 
    DECLARE @SQL nvarchar(max) = N'SELECT TOP 1 @outputFromExec = Id FROM ' + quotename(@dbName) + N'..myTbl'
    exec sp_executesql @SQL, N'@outputFromExec int out', @siteId out
    select @siteId