OcelotcR
OcelotcR

Reputation: 97

Syntax error on INSERT INTO ... SELECT statement (Access SQL)

I am trying to insert a field 'SID' Value into tbl1, But to get the SID It must reference the forename and surname to another table (tbl2) to get the SID, I then have used the following SQL Statement and subsequent code.

    Dim sqlquery As String = "INSERT INTO tblPayments (StudentID,Payment,PaymentDate) VALUES (SELECT StudentID FROM tblStudents WHERE Forename = @Forename AND Surname = @Surname , Payment = @SPaid, PaymentDate = @todaysdate)"

    Dim sqlcommand As New OleDbCommand
    With sqlcommand

        .CommandText = sqlquery

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

        .Connection = conn

        .ExecuteNonQuery()
    End With
    MsgBox("query executed, closing connection")
    conn.Close()

Yet, the SQLQuery is giving the error :

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll Additional information: Syntax error in query expression 'SELECT StudentID FROM tblStudents WHERE Forename = @Forename AND Surname = @Surname'.

But I can not see what is wrong with the part of the statement that is specified as wrong, can someone tell me where its wrong please?

Upvotes: 1

Views: 6176

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1271241

I think the error is very evident. The syntax for insert . . . select does not use the values keyword:

INSERT INTO tblPayments(StudentID, Payment, PaymentDate) 
    SELECT StudentID,  @SPaid, @todaysdate
    FROM tblStudents
    WHERE Forename = @Forename AND Surname = @Surname;

Upvotes: 3

Related Questions