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
3
  • use takes a database name, not a string. Commented Jul 15, 2016 at 7:02
  • 1
    Possible duplicate of sql use statement with variable Commented Jul 15, 2016 at 7:03
  • 1
    You can use Dynamic SQL or Hard coded IF statements. Commented Jul 15, 2016 at 7:07

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

It is worth to mention that DB1 is accessible only inside session of Dynamic query
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.