将记录添加到从另一个表中获取数据的字段

时间:2014-01-15 22:22:19

标签: vb.net ms-access

我目前正在尝试向表中添加新记录,我们称之为'tbl1'。这包含字段

ID | SID | Payment | PaymentDate | TID 

SID字段当前从另一个表中获取其值,我们称之为'tbl2'这包含字段

SID | Forename | Surname | Location

我有一个表单,它将付款记录添加到tbl1,它成功添加字段 ID 付款 PaymentDate 。这一切都很好,但表单不包含 SID 的提交框,这是因为用户很难记住 SID 。 因此,他们在表单中输入一个forename和username。

如果从表单中获取Forename和Surname,我将如何从 tbl2 检索 SID ,然后将 SID 应用到 TBL1

我尝试过双重SQL语句,如:

SELECT tbl2.Forename, tbl2.Surname FROM tbl2 WHERE tbl2.Forename = (FromInputForename) , tbl2.surname = (FOrmInputSurname)

根据我的理解,这应该得到与之相关的记录,然后从那里我应该能够检索 SID

但这没有用,如果你明白我来自哪里,你能帮助我吗?

我试过了:

'Declaring the connection route
Public connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data TestDB.accdb"
'The cursor
Public conn As New OleDbConnection(connstring)

Private Sub Addrecordbtn_Click(sender As Object, e As EventArgs) Handles Addrecordbtn.Click
    SPaid = Paidtxt.Text
    'Checking if connection is open.
    If conn.State = ConnectionState.Closed Then
        conn.Open()
    End If
    'SQL Query command for ADDING
    Dim sqlquery1 As String = "INSERT INTO tbl1 (Payment,PaymentDate) VALUES (@SPaid,@todaysdate)"
    'Creating the command itself.
    Dim sqlcommand As New OleDbCommand
    With sqlcommand
        'Telling what query
        .CommandText = sqlquery
        '  Paramaters to add with values.
        .Parameters.AddWithValue("@SPaid", SPaid)
        .Parameters.AddWithValue("@todaysdate", Today.Date)
        '   Selecting the connection
        .Connection = conn
        '  Executing the non query
        .ExecuteNonQuery()
    End With
    Dim sqlquery2 As String = "SELECT tbl2.Forename, tbl2.Surname FROM tbl2 WHERE tbl2.Forename = Forenametxt.text , tbl2.surname = Surnametxt.text"
    Dim da As OleDbDataAdapter = New OleDbDataAdapter(sqlquery2, conn)
    Dim ds As DataSet = New DataSet
    da.Fill(ds, "Payments")
    Dim dt As DataTable = ds.Tables("Payments")
    'Will then go on to display data.
    conn.Close()
End Sub

1 个答案:

答案 0 :(得分:3)

INSERT INTOSELECT声明

一起使用
INSERT INTO tbl1 (SID,Payment,PaymentDate) 
(SELECT SID, @SPaid, @todaysdate 
FROM tbl2
WHERE Forename = @Forename AND Surname = @Surname)

然后将forename和surname参数添加到命令

.Parameters.AddWithValue("@SPaid", SPaid)
.Parameters.AddWithValue("@todaysdate", Today.Date)
.Parameters.AddWithValue("@Forename ", Forenametxt.text)
.Parameters.AddWithValue("@Surname", Surnametxt.text)

请注意,如果在Forename中找不到Surenametbl2,则新行不会添加到tbl1 另一方面,@ Adrian在评论中提到 - 如果在tbl2中有多个用户,则会创建多个行。