简体   繁体   English

将SQL查询转换为vb.net

[英]Convert SQL Query to vb.net

Can help me to run the SQL Query in VB.NET .This is the query for converting table data in to csv 可以帮助我在VB.NET中运行SQL查询。这是将表数据转换为csv的查询

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 

First select required records into dataset 首先选择所需的记录到数据集中

And then use the following function to convert dataset into CSV file. 然后使用以下函数将数据集转换为CSV文件。

Function to convert dataset to 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

Taken from following links 摘自以下链接

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

If you want to do with my sql side thru VB.net. 如果您想通过VB.net与我的SQL一起使用。

Then you can create stored procedure 然后您可以创建存储过程

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

And then call this procedure from the from vb.net 然后从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

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM