Question : how to use dynamic SQL to assign a value to a variable when part of the SQL is a variable

I need to have a dynamic proc that will decide what DB to use based on the date. Once that is determined I need to use a dynamic statement to assign the max Uid (Unique ID) from a table in the TBD database to a variable like @MaxUID.

Below is what I have been trying and I keep getting "must declare scalar variable @MaxUID'.

If I print the SQL, then copy \ paste and execute it...it works...I am stuck. I am running SQL 2008 although I don't think that matters.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
declare @year nvarchar(4), @dbname nvarchar(8)
 
select @year = YEAR(getdate())
set @dbname = 'DB'+@year
set @sqlcmd = 'declare @MaxUID varchar(17) select @MaxUID = MAX(UIDnum) from '+@dbname+'.ARCHDATA.ARCHIVE'
execute sp_executesql @sqlcmd
print @sqlcmd

Answer : how to use dynamic SQL to assign a value to a variable when part of the SQL is a variable

declare @year nvarchar(4), @dbname nvarchar(8)
declare @MaxUID varchar(17)
declare @sqlCmd nvarchar(4000)
select @year = YEAR(getdate())
set @dbname = 'DB'+@year
set @sqlcmd = 'select @MaxUID = MAX(UIDnum) from '+@dbname+'.ARCHDATA.ARCHIVE'
execute sp_executesql @sqlcmd, N' @MaxUID varchar(17) output', @MaxUID output
print @sqlcmd

Random Solutions  
 
programming4us programming4us