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?
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"" " & "-S " & ServerName & " -d " & DatabaseName & " -Q " & QueryToExceute & " -s" & "," & " -o" & "C:\TestQuery.xlsx"
Dim wsh As Object = CreateObject("WScript.Shell")
'Using WScript to execute Stuff
wsh = CreateObject("WScript.Shell")
wsh.Run(Command)
I tried process class as well which is not working. Below is my 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 " & ServerName & "-d" & DatabaseName & "-Q" & QueryToExceute & "-s" & "," & "-o" & "C:\Testing1.xlsx"
Process.StartInfo.WorkingDirectory = "C:\users\rahul.wankhade\Desktop"
Process.Start()
Process.WaitForExit()