Consulting

Results 1 to 6 of 6

Thread: Solved: insert query

  1. #1
    VBAX Expert
    Joined
    Jan 2005
    Posts
    574
    Location

    Solved: insert query

    Can anyone tell me how to amend my query please to account for the fact that my first field is an autonumber

    Thanks

    Gibbo

    [VBA]
    strSQL = "INSERT INTO tbl_Test VALUES ('" & _
    Me.TextBox1 & "', '" & _
    Me.TextBox2 & "', '" & _
    Me.TextBox3 & "', '" & _
    Me.TextBox4 & "', '" & _
    Me.TextBox5 & "')"
    cn.Execute strSQL
    [/VBA]

  2. #2
    VBAX Expert xCav8r's Avatar
    Joined
    May 2005
    Location
    Minneapolis, MN, USA
    Posts
    912
    Location
    Add the column names to your SQL statement for which you're inserting values, but omit the field with the autonumber. It'll be incremented automatically. The same applies for any columns that have default values that you don't want to override. Example:
    CREATE TABLE tblExample
    (
    lngAutoNumber AUTOINCREMENT,
    strFirstName TEXT(30),
    strLastName TEXT(50),
    lngNumber INT
    );
    
    INSERT INTO tblExample (strFirstName, strLastName, lngNumber)
    VALUES ('John', 'Smith', 66);
    Li'l helper routine:

    [VBA]Option Compare Database
    Option Explicit

    'Long names
    Function SingleEnquotedString(StringToEnquote As String) As String
    SingleEnquotedString = "'" & StringToEnquote & "'"
    End Function

    'Abbreviations
    Function EnqStr1(Data As String) As String
    EnqStr1 = "'" & Data & "'"
    End Function

    Sub DoStuff()
    Dim strSQL As String
    strSQL = "INSERT INTO tblExample (strLastName, strFirstName, lngNumber)" _
    & vbNewLine & "VALUES (" _
    & EnqStr1(Me.TextBox1.Value) & "," & vbNewLine _
    & EnqStr1(Me.TextBox2.Value) & "," & vbNewLine _
    & EnqStr1(Me.TextBox3.Value) & ");"
    End Sub[/VBA]

  3. #3
    VBAX Expert
    Joined
    Jan 2005
    Posts
    574
    Location
    Thats looks really good

    I ll have a play tomorrow

    Thanks for looking

    Gibbo

  4. #4
    VBAX Expert
    Joined
    Jan 2005
    Posts
    574
    Location
    Also can you tell me the meaning of Option Compare Database as its a new one on me

    Cheers

    Gibbo

  5. #5
    VBAX Expert xCav8r's Avatar
    Joined
    May 2005
    Location
    Minneapolis, MN, USA
    Posts
    912
    Location

  6. #6
    VBAX Expert
    Joined
    Jan 2005
    Posts
    574
    Location
    Thanks works great

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •