基于vb.net中另一个SQL Server表中显示行的显示列

时间:2019-05-08 02:36:21

标签: vb.net sql-server-2008-r2

我对vb.net相当陌生。如何在vb.net中将行数据值显示为列名?

给出一些表结构。

表1及其原始列和示例数据:

RECEIPTNO    PIZZA   NOODLES  BURGER   BEVERAGES
--------------------------------------------------
  100          35      0        12          5

表2中仅包含两行数据:

FOODNAME  FOODTYPE
------------------
NOODLES    ASIAN FOOD
BEVERAGES  BEVERAGES

预期的表1将在表2的每一行显示食物名称。

RECEIPTNO  NOODLES  BEVERAGES
------------------------------
   100       0          5

谢谢。

1 个答案:

答案 0 :(得分:1)

首先,我从Table2下载以从Table1获得所需的列。遍历结果将构建SELECT语句。

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim dt As New DataTable
    Dim dt2 As New DataTable
    Using cn As New SqlConnection("Your connection string")
        Using cmd As New SqlCommand("SELECT FOODNAME FROM Table2;", cn)
            cn.Open()
            dt.Load(cmd.ExecuteReader)
            cn.Close()
        End Using

        Dim sqlSelect = "SELECT RECEIPTNO"
        For Each row As DataRow In dt.Rows
            sqlSelect &= "," & row("FOODNAME").ToString
        Next
        sqlSelect &= " FROM Table1;"
        Using cmd As New SqlCommand(sqlSelect, cn)
            cn.Open()
            dt2.Load(cmd.ExecuteReader)
        End Using
    End Using
    DataGridView1.DataSource = dt2
End Sub