如何在VB.NET中正确执行带多表JOIN和WHERE过滤的SELECT查询
在VB.NET中执行多表关联SQL查询的实现方案
你已经在SSMS验证通过的SQL语句不需要修改,可以直接在VB.NET中通过ADO.NET类库执行,以下是标准实现方式:
前置配置
首先在VB.NET代码文件顶部引入命名空间:
Imports System.Data.SqlClient Imports System.Configuration ' 若要从配置文件读取连接字符串需要引入
连接字符串建议统一存放在App.config的<connectionStrings>节点中,示例配置:
<connectionStrings> <add name="FVMASTERConn" connectionString="Data Source=你的SQL服务器地址;Initial Catalog=FVMASTER;User ID=登录账号;Password=登录密码;" providerName="System.Data.SqlClient"/> </connectionStrings>
基础实现代码(返回查询结果为DataTable)
' 1. 定义你已经验证通过的SQL语句,VB14及以上版本支持直接写多行字符串,低版本可以用&拼接 Dim querySql As String = " 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 " ' 2. 从配置文件获取连接字符串 Dim connStr As String = ConfigurationManager.ConnectionStrings("FVMASTERConn").ConnectionString Dim resultDt As New DataTable() ' 3. Using语句自动释放资源,无需手动关闭连接 Using conn As New SqlConnection(connStr) Using cmd As New SqlCommand(querySql, conn) conn.Open() ' 执行查询加载结果到DataTable Using adapter As New SqlDataAdapter(cmd) adapter.Fill(resultDt) End Using End Using End Using ' 后续可直接遍历resultDt获取查询结果
注意事项
- 若查询中的过滤条件为动态值(比如需要从界面输入获取
th.Code、th.StationID的值),必须使用参数化查询,禁止直接拼接SQL字符串,避免SQL注入风险,参数化写法示例:
' 修改SQL语句里的固定值为参数占位符 Dim querySql As String = " 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=@Code and th.StationID=@StationID and left(odo.OptionCode,1) = 'H' order by th.SchedID, th.UnitID, th.MasterKey " ' 给SqlCommand添加参数 cmd.Parameters.AddWithValue("@Code", 你的动态Code值) cmd.Parameters.AddWithValue("@StationID", 你的动态StationID值)
- 若需要逐行读取查询结果而非一次性加载到DataTable,可以使用
SqlDataReader实现:
Using reader As SqlDataReader = cmd.ExecuteReader() While reader.Read() ' 按列名读取对应的值 Dim schedId = reader("SchedID").ToString() Dim optionCode = reader("OptionCode").ToString() ' 处理每行数据逻辑 End While End Using
内容的提问来源于stack exchange,提问作者Martin
相关产品推荐
相关产品推荐

