2012-12-06 74 views
0

能帮我在VB.NET。这运行SQL查询是在转换表中的数据为csv查询转换SQL查询到vb.net

USE newdb 
GO 
-- Check Table Column 
SELECT * 
FROM accountexample 
GO 
-- Get CSV values 
SELECT SUBSTRING(
(SELECT ' ' + s.BPl + ',' + s.Lo + ',' + s.Ltion + ',' + s.Ite + ',' + s.HNO + ',' + s.QNo + ',' + s.Country + ',' + s.STATE + ',' + s.Rem + CHAR(10) 
    FROM accountexample s 
ORDER BY s.BPl 
FOR XML PATH('')),2,200000) AS CSV 
GO 
+0

你不转换SQL到VB。净。您可以使用VB.NET运行SQL查询。那是你想要做什么? – dtbarne

+0

重复http://stackoverflow.com/questions/5610536/how-do-i-run-this-sql-query-in-vb-net – dtbarne

+0

显示错误 - Dim QUERY As String =“SELECT * from DB。 dbo.accountexample (“SELECT''+ s.BPl +','+ s.Lo +','+ s.Ltion +','+ s.Ite +','+ s.HNO +','+ s.QNo +','+ s.Country +','+ s.STATE +','+ s.Rem + CHAR(10)FROM DB.dbo.accountexample s ORDER BY s.BPl FOR XML PATH('' )),2,200000)AS CSV“) –

回答

0

首先选择需要记录到数据集

然后使用以下函数将数据集转换为CSV文件。

功能到数据集转换为CSV

Sub SetDataTable_To_CSV(ByVal dtable As DataTable, ByVal path_filename As String, ByVal sep_char As String) 

    Dim writer As System.IO.StreamWriter 

    Try 

     writer = New System.IO.StreamWriter(path_filename) 



     Dim _sep As String = "" 

     Dim builder As New System.Text.StringBuilder 

     For Each col As DataColumn In dtable.Columns 

      builder.Append(_sep).Append(col.ColumnName) 

      _sep = sep_char 

     Next 

     writer.WriteLine(builder.ToString()) 



     For Each row As DataRow In dtable.Rows 

      _sep = "" 

      builder = New System.Text.StringBuilder 



      For Each col As DataColumn In dtable.Columns 

       builder.Append(_sep).Append(row(col.ColumnName)) 

       _sep = sep_char 

      Next 

      writer.WriteLine(builder.ToString()) 

     Next 

    Catch ex As Exception 



    Finally 

     If Not writer Is Nothing Then writer.Close() 

    End Try 

End Sub 

取自以下链接

http://redsouljaz.com/2010/06/03/vb-net-set-data-table-to-csv-file/

如果你想与我的SQL方通VB.net做。

那么您可以创建存储过程

CREATE PROC ConvertCSV 
AS 
BEGIN 
    SELECT SUBSTRING(
(SELECT ' ' + s.BPl + ',' + s.Lo + ',' + s.Ltion + ',' + s.Ite + ',' + s.HNO + ',' + s.QNo + ',' + s.Country + ',' + s.STATE + ',' + s.Rem + CHAR(10) 
    FROM accountexample s 
ORDER BY s.BPl 
FOR XML PATH('')),2,200000) AS CSV 
END 

然后调用从这个过程从vb.net

Dim con As New SqlConnection("Data Source=<datasource>;Initial Catalog=<databasename>;User ID=<username>;Password=<password>") 
con.Open() 

Dim cmd As New SqlCommand("ConvertCSV", con) 

Try 
    cmd.CommandType = CommandType.StoredProcedure 
    cmd.ExecuteNonQuery() 

Finally 
    If cmd IsNot Nothing Then cmd.Dispose() 
    If cn IsNot Nothing AndAlso cn.State <> ConnectionState.Closed Then cn.Close() 
End Try 

希望这有助于