2

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.

2
  • 3
    I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". Commented Oct 12, 2013 at 20:17
  • @JohnSaunders Ah, sorry didn't realize. Thanks. Commented Oct 12, 2013 at 20:18

1 Answer 1

2

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(); 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the quick reply. I set the default to SSMS and tried your approach, and sometimes it works and sometimes it doesn't. I think I narrowed it down to needing to be connected to a database. If SQL server isn't connected it will open multiple windows, otherwise the files will open in the the window which is already connected. Is there a way to not have to set the default application? I'm creating this as a tool for some coworkers.
This is really close! Problem I have now is that SSMS opens up but claims that the files can't be found and will not be loaded. I checked and the files are indeed there. I think the issue is that the paths have spaces (e.g. C:\Documents and Settings\...) because when I put the sql files in the root C:\ directory they open up just fine. I'm gonna work with it some more but thanks for all your help!
I think I got it, I have to wrap the file names in quotes like so: "\"" + filename + "\""
@vince88 Perfect catch again. Updated the answer to reflect it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.