Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop the "Changed database context to ..." message

Tags:

Is there some way to stop the Changed database context to ... message when the piece of SQL has a USE database in it ?

like image 372
SteveC Avatar asked May 02 '12 11:05

SteveC


People also ask

How do you stop a SQL database from being used?

Start, stop, or restart an instance of the SQL Server AgentIn Object Explorer, connect to the instance of the Database Engine, right-click SQL Server Agent, and then select Start, Stop, or Restart.

Which command to use for changing the context of the database to different database?

Try using sp_MSforeachdb (be aware, it is undocumented). Put either of these in your loop against the db names and this should solve your problem. Put either of these in your loop against the db names and this should solve your problem."


2 Answers

You need to set the errorlevel of sqlcmd, which defaults to 0. Note: don't confuse the errorlevel here with the exit code of sqlcmd that is returned to, say, cmd.exe as the ERRORLEVEL.

To disable this message for all of an sqlcmd session, use the -m commandline option:

sqlcmd -m 1 <other options> 

To disable this message for a block of code, use the :setvar batch command:

USE [mydb] GO  -- Disable message for next USE command :setvar SQLCMDERRORLEVEL 1 USE [mydb] GO  -- Reenable :setvar SQLCMDERRORLEVEL 0  ... 

To use the :setvar (or other SQLCMD batch commands) in Management Studio, you need to enable the SQLCMD mode for the query window you're in (menu "Query / SQLCMD Mode"). You'll see that it is enabled, when lines starting with ':' have a gray background.

like image 94
Christian.K Avatar answered Sep 23 '22 14:09

Christian.K


I release updates by having SQLCMD run all my .sql scripts in a directory. But when you start everything with a USE myDB you get a repetitive changed context message in the log file, which is dull. So I use this one liner instead. If the context is actually changed, you still get the message, which is good.

IF EXISTS(SELECT DB_NAME() WHERE DB_NAME() not IN ('myDB')) USE MyDB

like image 24
Jolly Tom Avatar answered Sep 22 '22 14:09

Jolly Tom