SQLCMD将数据导出为CSV

时间:2017-03-16 08:56:25

标签: .net sql-server vb.net sqlcmd

我正在使用SQLCMD(SQL命令提示符)将数据导出到CSV,但它引发了与访问控制相关的问题:

  

用户登录失败' MEA \ UserName' ....无法打开数据库" C:\ ABC.mdf"但是User(UserName)已经为该数据库提供了完全访问控制。

以下是我的代码:

Dim ServerName As String = System.Net.Dns.GetHostName()

Dim DoubleQuote As String = Chr(34)

Dim DatabaseName As String = DoubleQuote & "C:\Giv 15Mar2017\WindowsApplication1_Givaudan_new\WindowsApplication1_Givaudan_new\WindowsApplication1\Database\ABC.mdf" & DoubleQuote

Dim QueryToExceute As String = DoubleQuote & "set nocount on;Select  * from EKPO" & DoubleQuote

Dim ExportFileName As String = "C:\Data\TableData.csv"

Dim QueryToExceute1 As String = DoubleQuote & "set nocount on;Select * from EKPO" & DoubleQuote

Dim ExportFileName1 As String = "C:\Data\TableDataCorrection.csv"

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 " &
QueryToExceute1 & " -o " & ExportFileName & "  -s""|"" -W"

Process.StartInfo.WorkingDirectory = "C:\Data"

Process.Start()
Process.WaitForExit()

1 个答案:

答案 0 :(得分:0)

您必须指定数据库名称而不是MDF路径。

sqlcmd -S "YOURSERVER\YOURINSTANCE" -d YOURDATABASENAME

即使您使用LocalDb,也无法直接访问MDF文件,但必须使用此sintax:

sqlcmd -S "(localdb)\MSSQLLocalDB" -d YOURDATABASENAME