1

I'm writing a SQL script which is executed as part of a series of SQL scripts. I cannot access the other scripts nor do I have control over the "series-execution"-logic.

I want to change the database within my script (USE someDB), however, I want to make sure that after my script has run the previous DB is the current DB again. Is there some kind of pushd/popd for database usage? An alternative, e.g., by somehow writing the current DB into a temporary variable?

D.R.
  • 20,268
  • 21
  • 102
  • 205

1 Answers1

0

I don't know about any pushd/popd functionality, but the way to get the current database name is use the DB_NAME() function like this:

SELECT DB_NAME()
chrischu
  • 3,047
  • 3
  • 27
  • 44
  • I couldn't find a way to use a variable as the parameter of the `USE` statement - do you know how? – D.R. Aug 25 '16 at 14:49
  • No you can't, 2 options i use, dynamic sql or `IF @A= 'a' USE X IF @A= 'b' USE Y` – MWillemse Aug 25 '16 at 14:56
  • Maybe there is an alternative pushd/popd solution instead...the temp-var-approach is already a workaround, and I really don't wanna have a workaround in place which needs additional workarounds to workaround... – D.R. Aug 25 '16 at 15:11