vince88
vince88

Reputation: 3299

Open multiple files in an existing instance of SQL Server

So I've written a simple exe that will extract sql files from a zipped folder and open them in SQL Server Studio. It works great except that sometimes there will be multiple sql files to open, which then causes multiple SQL Server Instances to open. How can I make the files all open in one instance?

This is what I'm trying so far:

foreach (string sqlFile in files)
{ 
     Process sqlServer;

     if (Process.GetProcessesByName("Ssms").Length > 0)
          sqlServer = Process.GetProcessesByName("Ssms")[0];
     else
          sqlServer = new Process();

     sqlServer.StartInfo.FileName = sqlFile;
     sqlServer.Start();                                                    
}

Sometimes a file will magically open in an existing SQL Server window but I haven't figured out why.

Upvotes: 2

Views: 460

Answers (1)

Alireza
Alireza

Reputation: 10476

I couldn't find any way to use an existing SSMS (sorry!), but fortunately, I found SSMS command line very useful. It can be fed with the name of the server and/or the instance to connect with switch -S. It also logins with Windows Authentication with switch -E. Take a look at its options via SSMS /? and choose what fits your problem best. Anyway I tested the following code with and without a pre-existing SSMS instance connected/disconnected:

string serverName = "myservername";    
var sepratedFiles = string.Join(" ", files.Select(p=>"\"" +p +"\"");

Process sqlServer = new Process();
sqlServer.StartInfo.FileName = "SSMS";
sqlServer.StartInfo.Arguments = string.Format("-S {0} {1}", serverName, sepratedFiles );
sqlServer.Start();

Upvotes: 2

Related Questions