0

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
divibisan
  • 11,659
  • 11
  • 40
  • 58
Aboli Ogale
  • 87
  • 1
  • 9

1 Answers1

0

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
StackUser
  • 5,370
  • 2
  • 24
  • 44
  • It is worth to mention that `DB1` is accessible only inside session of Dynamic query – Pரதீப் Jul 15 '16 at 07:11
  • This is working. But It does not solved my problem. I am writing a procedure which will take database name as parameter and it will print all the list procedures of that database. I am getting required information from sys.procedures table. But I am stuck at how to use database name which I will pass as parameter to SP inside "use" statement. – Aboli Ogale Jul 15 '16 at 07:21