I want to use a local variable with a use statement in SQL Server. I searched but could not find a proper solution.
declare @var varchar(100)
set @var = 'DB1'
use @var
Try like this,
DECLARE @var VARCHAR(100)
,@SQL NVARCHAR(max) = ''
SET @var = 'DBRND'
SET @sql = 'select name From ' + @var + '.sys.procedures'
EXEC SP_EXECUTESQL @SQL
DB1 is accessible only inside session of Dynamic query
usetakes a database name, not a string.Dynamic SQLor Hard codedIFstatements.