【问题标题】:Using select query in vb.net在 vb.net 中使用选择查询
【发布时间】:2021-11-01 01:09:19
【问题描述】:

我试图弄清楚如何在 vb.net 中正确使用选择查询。我尝试使用的查询使用连接函数来连接多个表。我也有一个 where 过滤器。下面是在 MS SQL Server Management Studio 中工作的查询。这里的任何人都可以将我推向正确的方向或知道我可以用来执行此查询的语法/格式吗?

select th.*, odo.OptionCode
from FVMASTER..trackinghistory th
join FVMASTER..OrderDetailOptions odo on odo.odKey=th.odKey
join FVMASTER..MasterPartOptions mpo on mpo.Code=odo.OptionCode and mpo. 
[Group]=odo.optiongroup 
and mpo.QuestionKey='KGLASS' and OptionType=5
where th.DateTime>DATEADD(DAY,-4,getdate()) and th.Code='__A__' and th.StationID='HO4' and 
left(odo.OptionCode,1) = 'H'
order by th.SchedID, th.UnitID, th.MasterKey

【问题讨论】:

  • 在 .net 中使用 sql 的通常方法是使用实​​体框架
  • 您在上一个问题中已经有了问题的答案:SQL Select query in VB.NET

标签: sql vb.net


【解决方案1】:

这是在 ADO.net 中完成的方式。您将需要在文件的顶部。

Imports System.Data.SqlClient

sqlString 的这一行有问题。一段时间后你不会想要一个空格。

join FVMASTER..MasterPartOptions mpo on mpo.Code=odo.OptionCode and mpo.

您应该能够将 Select 语句从 SSMS 直接复制并粘贴到 vb.net 代码中。

将您的数据访问代码与用户界面代码分开。您的所有参数似乎都是硬编码的。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim dt = GetThData()
    DataGridView1.DataSource = dt
End Sub

Private Function GetThData() As DataTable
    Dim sqlString = "select th.*, odo.OptionCode
from FVMASTER..trackinghistory th
join FVMASTER..OrderDetailOptions odo on odo.odKey=th.odKey
join FVMASTER..MasterPartOptions mpo on mpo.Code=odo.OptionCode 
and mpo. 
[Group]=odo.optiongroup 
and mpo.QuestionKey='KGLASS' and OptionType=5
where th.DateTime>DATEADD(DAY,-4,getdate()) and th.Code='__A__' 
and th.StationID='HO4' and 
left(odo.OptionCode,1) = 'H'
order by th.SchedID, th.UnitID, th.MasterKey;"
    Dim dt As New DataTable
    Using cn As New SqlConnection("Your connection string"),
            cmd As New SqlCommand(sqlString, cn)
        cn.Open()
        Using reader = cmd.ExecuteReader
            dt.Load(reader)
        End Using
    End Using
    Return dt
End Function

【讨论】:

  • 这可能是我所追求的。我现在遇到的问题是 DataGridView1 没有声明,你知道我该如何解决这个问题吗?
  • 当我删除 where 过滤器时,它确实会做一些事情。我可以看到应用程序使用了大量内存并且应用程序变得非常慢,可能是因为它请求了大量数据。问题是它从不显示包含数据的表格。
  • 如果查询在 SSMS 中运行,它将在 vb.net 中运行。当您说大量数据时,SSMS 中返回了多少行?就 DataGridView1 而言,将控件添加到表单中。这是您添加的第一个网格的默认名称。随意命名并更改代码中的名称。
  • 您是否修复了我在回答中提到的 Select 中的行?以句点结尾的行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-06
  • 1970-01-01
  • 2016-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多