3
USE master
GO

DECLARE @DbName nvarchar(MAX)
SET @DbName = N'DataBase'

ALTER DATABASE @DbName
SET SINGLE_USER WITH ROLLBACK IMMEDIATE

ALTER DATABASE @DbName SET OFFLINE WITH NO_WAIT
GO

ALTER DATABASE @DbName SET ONLINE
GO

ALTER DATABASE @DbName
SET MULTI_USER
GO

I know i can use EXEC but it's a bit ugly....

5
  • 1
    You can't parameterise object references in most DML/DDL. You do indeed need EXEC / sp_executesql, and to build up some dynamic queries. Commented Feb 1, 2012 at 9:32
  • 1
    I assume you've seen this question stackoverflow.com/questions/9093478/… which suggests EXEC. That might be the only way. Commented Feb 1, 2012 at 9:32
  • 2
    @Ray you linked to my own question :-P Commented Feb 1, 2012 at 19:49
  • @AK_ ha! My bad. Copy and paste gone wrong. Don't have what I meant to link to anymore. Commented Feb 1, 2012 at 20:44
  • Does this answer your question? How can I do something like: USE @databaseName Commented Jun 24, 2021 at 9:59

4 Answers 4

6

It is impossible to use DB name from variable.

Use Dynamic Querying, even if it is ugly.

Sign up to request clarification or add additional context in comments.

Comments

2

You can't use the database name in a variable.

You have several options:

Comments

0

Firstly, you can't parameterise DDL statements like this. Secondly, GO is a batch terminator and parameters won't be available after this.

Comments

0

I don't recall if MSSqlServer allows the same flexibility as Oracle and MySQL, but in those you can set the default database for each connection. If the queries and statements do not specify a database (use (dbname)), it uses the default. Perhaps that is sufficient parametrization for your purposes?

Comments

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.