title: How to run SQLCMD script using VB.NET
body: <p>I am trying to execute SQL query using SQLCMD (SQL Command Prompt) using VB.NET code. I am connecting to the server using Windows Shell script and executing a query and storing the result-set in Excel file. Below is my code which is not working.
  What is missing in below code?</p>
  
  <pre><code>    Dim Command
      Dim ServerName As String
      Dim DatabaseName As String
      Dim QueryToExceute As String
  
      ServerName = "IN2175533W1"
      DatabaseName = "C:\FileDirectory\XYZ.mdf"
      QueryToExceute = "Select * from Table_Name"
  
     Command = """C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\SQLCMD.EXE"" " &amp; "-S " &amp; ServerName &amp; " -d " &amp; DatabaseName &amp; " -Q " &amp; QueryToExceute &amp; " -s" &amp; "," &amp; " -o" &amp; "C:\TestQuery.xlsx"
  
      Dim wsh As Object = CreateObject("WScript.Shell")
  
      'Using WScript to execute Stuff
      wsh = CreateObject("WScript.Shell")
      wsh.Run(Command)
  </code></pre>
  
  <p>I tried process class as well which is not working. Below is my code:</p>
  
  <pre><code>    Dim Command
      Dim ServerName As String
      Dim DatabaseName As String
      Dim QueryToExceute As String
  
      ServerName = "IN2175533W1"
      DatabaseName = "C:\ABC\XYZ.mdf"
      QueryToExceute = "Select * from Quality"
  
  
          Dim Process = New Process()
      Process.StartInfo.UseShellExecute = False
      Process.StartInfo.RedirectStandardOutput = True
      Process.StartInfo.RedirectStandardError = True
      Process.StartInfo.CreateNoWindow = True
      Process.StartInfo.FileName = "SQLCMD.EXE"
      Process.StartInfo.Arguments = "-S " &amp; ServerName &amp; "-d" &amp; DatabaseName &amp; "-Q" &amp; QueryToExceute &amp; "-s" &amp; "," &amp; "-o" &amp; "C:\Testing1.xlsx"
  
      Process.StartInfo.WorkingDirectory = "C:\users\rahul.wankhade\Desktop"
      Process.Start()
      Process.WaitForExit()
  </code></pre>