1

I have the following SQL statement for adding records in Microsoft Access. When I run the statement, every field gets added correctly except the boolean field, which should always be false. However, it always adds the record with the default boolean value (true).

Dim strSQL As String
strSQL = "INSERT INTO Part VALUES ('" & Me.IdPartPrimary.Value & "', '" & Me.NamePartPrimary.Value & "', '" & Me.BrandPartPrimary.Value & "', '" & Me.ModelPartPrimary.Value & "', '" & Me.FunctionPartPrimary.Value & "', 0, '" & Me.FatherPartPrimary.Value & "', '" & Me.ProviderPartPrimary.Value & "', '" & Me.AmountPartPrimary.Value & "');"
DoCmd.RunSQL strSQL

Things I've tried:

  • Putting the 0 between ' '
  • Replacing the 0 with the word false, False and No

I can't set false to be the default value because what I need is for it to be different from the default value

Table

Form

14
  • What's the "Boolean field" here? Can you share your table schema and clue is on your variables/values you are inserting here? Commented Aug 31, 2022 at 17:36
  • If fields are Yes/No type, don't use apostrophe delimiters. Those are only for text type field and Yes/No is number type. I don't understand your last statement. You can set 0 as DefaultValue in table design and then enter -1 if that is what you want. Commented Aug 31, 2022 at 17:39
  • @JNevill I added them to the post Commented Aug 31, 2022 at 17:41
  • Why don't you use BOUND form instead of SQL? Commented Aug 31, 2022 at 17:42
  • @June7 I tried that but it doesn't work, it still adds the record with the default value of the field Commented Aug 31, 2022 at 17:42

1 Answer 1

2

Binding form to table and running SQL to create record into same table will result in two new records. Do one or the other.

Do not include autonumber field in the INSERT action. Will have to explicitly list the fields to receive data.

If you want new record to always have 0 value in the Yes/No field, then set that as DefaultValue in table design, otherwise use a constant in the SQL concatenation to specify.

strSQL = "INSERT INTO Part(..., Primary_Part, ...) VALUES(" & ... & ", 0, " & ... & ")"

AFAIK, Access cannot execute multi-action SQL statements but SQL injection is still possible. If you want to explore use of Parameters in VBA, review How do I use parameters in VBA in the different contexts in Microsoft Access?

Another alternative to avoid SQL injection is to open a recordset, use its AddNew method to create a new record, and set value of each field. DAO.Recordset AddNew

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.