如何使用VB.NET运行SQLCMD脚本

时间:2017-03-11 09:05:56

标签: sql .net vb.net

我正在尝试使用VB.NET代码使用SQLCMD(SQL命令提示符)执行SQL查询。我使用Windows Shell脚本连接到服务器并执行查询并将结果集存储在Excel文件中。以下是我的代码无效。 以下代码缺少什么?

    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)

我也试过过程类,但是没有用。以下是我的代码:

    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()

2 个答案:

答案 0 :(得分:1)

这是我测试的内容,请注意我更改了服务器,数据库和查询以匹配我的机器。我正在通过VS2015使用字符串插值。

Module Module1
    Sub Main()
        Dim ServerName As String = "KARENS-PC"
        Dim DatabaseName As String = "C:\Data\NORTHWND.MDF"
        Dim DoubleQuote As String = Chr(34)
        Dim QueryToExceute As String =
            $"{DoubleQuote}SELECT CompanyName,ContactName FROM Customers{DoubleQuote}"
        Dim ExportFileName As String =
            $"{DoubleQuote}C:\Data\MyDataFromSqlServer.csv{DoubleQuote}"

        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} -E -Q {QueryToExceute} -o {ExportFileName} -h-1 -s"","" -w 700"
        Process.StartInfo.WorkingDirectory = "C:\Data"
        Process.Start()
        Process.WaitForExit()
        Console.WriteLine("Done")
        Console.ReadLine()

    End Sub
End Module

没有VS2015的传统方式

Module Module1
    Sub Main()
        Dim ServerName As String = "KARENS-PC"
        Dim DatabaseName As String = "NorthWindAzure"
        Dim DoubleQuote As String = Chr(34)
        Dim QueryToExceute As String =
            DoubleQuote & "SELECT CompanyName,ContactName FROM Customers" & DoubleQuote
        Dim ExportFileName As String =
            DoubleQuote & "C:\Data\MyDataFromSqlServer.csv" & DoubleQuote

        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 & " -E -Q " &
            QueryToExceute & " -o " & ExportFileName & "  -h-1 -s"","" -w 700"
        Process.StartInfo.WorkingDirectory = "C:\Data"

        Process.Start()
        Process.WaitForExit()
        Console.WriteLine("Done")
        Console.ReadLine()
    End Sub
End Module

答案 1 :(得分:0)

我要做的另一种方法是在代码下面,读取字符串对象中的所有代码,将其替换为Go来解析其他符号,然后逐个执行数组。

Sub ExecuteWithCommand()
    Try
        Dim sFile As FileInfo = New FileInfo(Directory.GetCurrentDirectory.ToString() & "\Script.sql")
        If (sFile.Exists = True) Then
            Dim dbObj = New SqlDataAccess()   
           'your SQL data-access class'
            Dim objReader As New System.IO.StreamReader(Directory.GetCurrentDirectory.ToString() & "\Script.sql")
            Dim scriptArr As String()
            Dim i As Integer
            dbObj.Command.CommandText = objReader.ReadToEnd.Replace("GO", "#")  
            'use any other symbol which you want, keeping in mind, its not used elsewhere in script'
            scriptArr = dbObj.Command.CommandText.Split("#")

            For i = 0 To scriptArr.Length - 1
                dbObj.Command.CommandText = scriptArr.GetValue(i)
                dbObj.Command.ExecuteNonQuery()
            Next

        End If
    Catch ex As Exception            
        Console.WriteLine(ex.Message)
    End Try