0

Alright this is completely baffling me. how do i switch between db's using C#? The below doesn't work. I also tried it using in SQL mgmt studio and it appears that Go needs to be on a line by itself to work.

sqlCmd.CommandText = @"USE [" + db + "] GO";

Any ideas?

1
  • 3
    have 2 connection strings then reference which one you need at the time Commented Jun 19, 2013 at 19:12

3 Answers 3

4

You shouldn't be trying to change the database in the context of the command object, you should change it at the SqlConnection level. See this MSDN

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

Comments

3

The connection string on your connection object will name a database. You should use a new connection object that refers to the new database.

1 Comment

Prolly more sensible than changing dbs on the fly, +1
0

GO is not part of SQL, that is something special Sql Server Management Studio (and some other Microsoft utilities) uses, it marks the seperation of "batches". Every GO would translate in to a ExecuteXXXXQuery action in C#.

I am assuming your code is more than what you posted so lets say your original query was

select * into #t from foo 
use [someOtherDatabase]
GO
insert into foo select * from #t

What this would be come in C# is

using(var cmd = SqlCommand("", connectionString))
{
    cmd.CommandText = @"select * into #t from foo
                        use [someOtherDatabase]";
    cmd.ExecuteNonQuery();
    cmd.CommandText = "insert into foo select * from #t";
    cmd.ExecuteNonQuery();
}

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.