执行内部联接

时间:2009-05-20 10:59:39

标签: vb.net ms-access

我正在尝试做一个内连接select语句,我从表中选择两个字段,而不是第二个表中与第一个表具有相同id的字段的所有记录。

代码如下:

    Dim conn As OleDbConnection
    Dim cmd As OleDbCommand

    Public Sub openDB()
        rsConn = New ADODB.Connection
        rsConn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\VFMS_DB.mdb;" & "Jet OLEDB:System Database=Security.mdw", "ADMIN", "1234")
    End Sub

    Public Function GetProdDetails(ByVal vegeID As Integer, ByRef dsTask As DataSet) As Integer

        Dim retCode As New Integer

        Dim da As OleDbDataAdapter

        Try
            Dim i As Integer = 0

            openDB2()

            da = New OleDbDataAdapter("SELECT [Vegetables Descriptions.Task], [Vegetables Descriptions.Description], [TasksOcc.When] FROM [Vegetables Descriptions] INNER JOIN [TasksOcc] ON [Vegetables Descriptions.DescID] = [TasksOcc.DescID] WHERE [Vegetables Descriptions.VegeID] = vegeID", conn)
            da.Fill(dsTask)

            retCode = 0

            conn.Close()
            Return retCode
        Catch ex As Exception
            MessageBox.Show(ex.ToString, ex.Message, MessageBoxButtons.OK)
            retCode = 1
            Return retCode
        End Try
    End Function

我得到一个例外:“名称[蔬菜描述.DescID]无效包围

如果我把它拿出来看起来如下,我会得到一个“不支持加入表达式”

        da = New OleDbDataAdapter("SELECT [Vegetables Descriptions.Task], [Vegetables Descriptions.Description], [TasksOcc.When] FROM [Vegetables Descriptions] INNER JOIN [TasksOcc] ON [DescID] = [DescID] WHERE [Vegetables Descriptions.VegeID] = vegeID", conn)

我尝试从网上下载示例,但不成功。

3 个答案:

答案 0 :(得分:5)

使用[Vegetables Descriptions].[DescID]代替[Vegetables Descriptions.DescID]。由于“蔬菜描述”包含空格,因此它必须是[]中唯一的名称。

答案 1 :(得分:4)

包装易读的行:

da = New OleDbDataAdapter("
  SELECT [Vegetables Descriptions].[Task], 
         [Vegetables Descriptions].[Description], 
         [TasksOcc].[When] 
  FROM   [Vegetables Descriptions] INNER JOIN [TasksOcc] 
         ON [Vegetables Descriptions].[DescID] = [TasksOcc].[DescID] 
  WHERE  [Vegetables Descriptions].[VegeID] = vegeID
", conn)

每个单个标识符都放在方括号中,而不是每个完整的名称。

顺便说一句:带有空格的表名是......嗯......他们不是我想做的。 ; - )

编辑:这在眼睛上更容易(您只需要使用带有“非标准”名称的表标识符的方括号,并且您可以使用别名):

da = New OleDbDataAdapter("
  SELECT d.Task, 
         d.Description, 
         t.When
  FROM   [Vegetables Descriptions] AS d INNER JOIN TasksOcc AS t
         ON d.DescID = t.DescID
  WHERE  d.VegeID = vegeID
", conn)         ''#  ^
                 ''#  |
                 ''#  /----- Not sure what this does in this query, though.

答案 2 :(得分:0)

插入此内容:

da = New OleDbDataAdapter("SELECT Descriptions.Task, Descriptions.Description, TasksOcc.When FROM Descriptions INNER JOIN TasksOcc ON TasksOcc.DescID = Descriptions.DescID WHERE Descriptions.VegeID = " & vegeID, conn)