it gives an error when i run a SQL script - sql

I'm trying to INSERT INTO with SQL in a table in VBA but it gives a error while running this script. why?
I was expecting it to add the values to the table but it gives an error instead, does anyone has the solution for this?
DoCmd.RunSQL "INSERT INTO tblScores (Student, Score, Date, ExamType, Lesson) VALUES (cbStudent.Value,txtScore.Value,txtDate.Value,cbExamType.value,cbLesson.Value);"
The error message:

The form values need to be concatenated to the SQL string, not being enclosed to it.
For example:
"WHERE ID =" & IdControl.Value
But this way is not recommended for various reasons. Best to create a temporary query and pass the values as parameters. If you need to run it frequently, create a permanent query and just call it - it will be slightly faster.
Const SQL As String = "PARAMETERS [Student] Text (255), [Score] IEEESingle, [Date] DateTime, [ExamType] Text (255), [Lesson] Text (255); " & _
"INSERT INTO tblScores (Student, Score, [Date], ExamType, Lesson) " & _
"SELECT [Student] AS [Student], [Score] AS [Score], [Date] AS [Date], [ExamType] AS [ExamType], [Lesson] AS [Lesson];"
Dim q As DAO.QueryDef
Set q = CurrentDb().CreateQueryDef("", SQL) 'temporary query
q.Parameters("[Student]").Value = cbStudent.Value
q.Parameters("[Score]").Value = txtScore.Value
q.Parameters("[Date]").Value = txtDate.Value
q.Parameters("[ExamType]").Value = cbExamType.Value
q.Parameters("[Lesson]").Value = cbLesson.Value
q.Execute
q.Close
Keep in mind I don't know the actual data-types of your table fields, so some of the params could be off - the score for example.

Try this:
Dim varStudent as String
.
varStudent = cbStudent
.
In SQL String: VALUES ( '" & varStudent & "', '" & varTxtScore & "'
'" = SingleQuote DoubleQuote

Related

Error 3346, trying to INSERT INTO, two consecutive tables

I have those two tables is MS Access :
lkpSchemaPIT :
| UID | lkpSchemaTitleEng |
|-----|--------------------------|
|--1--|---------Title1-----------|
|--2--|---------Title2-----------|
...
lkpSchemaPITChronology :
| ID | UID | PUID | Sort | Level | DateStart | DateEnd |
|----|-----|------|------|-------|-----------|---------|
|--0-|--1--|--0---|---5--|--2----|---Now()---|--NULL---|
...
The first table contains just nodes that i'm going to put in a treeview in access. I use the second table to construct the tree, but also keep track of all the parent that a node could've had through the years. You can see that the UID in the two tables are the same, but they have not a relationship between them, when I build the tree, I use a query with a join on it.
My problem is : When I want to add a new node in the lkpSchemaPIT table, I need to be able to add its "treeview" info as well (Parent, Sort, Level, etc.).
This is my code so far :
With CurrentDb
.Execute _
"INSERT INTO lkpSchemaPIT " & _
"(lkpSchemaTitleEng) " & _
"VALUES " & _
"('" & Title & "')"
.Execute _
"INSERT INTO lkpSchemaPITChronology VALUES (" & .OpenRecordset("SELECT ##IDENTITY").Fields(0) & ", " & [ParentID] & ", " & [NewSort] & ", " & [Level] & ", " & Date & ", null)"
End With
ParentID, NewSort, Level are 3 variables that have been determined before I call all this.
The "Date" parameters is the VBA function that returns the current date.
I know that the first INSERT INTO is working because a new value is displayed in my table. But the second INSERT INTO isn't working and I was able to get the error :
Error 3346 - Number of query values and destination fields are not the same.
Is anyone ever had this kind of problem ?
Once again, here is an example where parameterized queries would be invaluable as you avoid quote enclosures (including # for date/times) and string concatenation that conflates data and SQL together, rendering hard to read and maintain code.
MS Access allows the PARAMETERS clause where you can define the parameter placeholder names and data types and then in VBA you can bind values to such parameters using QueryDefs. No quotes needed or string interpolation.
SQL (save both as stored queries)
PARAMETERS TitleParam Text(255);
INSERT INTO lkpSchemaPIT (lkpSchemaTitleEng)
VALUES (TitleParam);
PARAMETERS UIDParam Long, PUIDParam Long, SortParam Long,
LevelParam Long, DateStart Datetime;
INSERT INTO lkpSchemaPITChronology (UID, PUID, [Sort], [Level], DateStart)
VALUES (UIDParam, PUIDParam, SortParam, LevelParam, DateStartParam);
VBA
...
Dim qdef As QueryDef
With CurrentDb
' FIRST QUERY
Set qdef = .QueryDefs("myFirstSavedAppendQuery")
qdef!TitleParam = [Title]
qdef.Execute dbFailOnError
' SECOND QUERY
Set qdef = .QueryDefs("mySecondSavedAppendQuery")
qdef!UIDParam = .OpenRecordset("SELECT ##IDENTITY").Fields(0)
qdef!PUIDParam = [ParentID]
qdef!SortParam = [NewSort]
qdef!LevelParam = [Level]
qdef!DateStart = Date()
qdef.Execute dbFailOnError
End With
Set qdef = Nothing

How to write a value into access database faster - VBA (excel)

I am trying to store the values inside an access database from excel using vba.
I have a form in Excel where I get the Inputs from the User.
On VBA, In the Locals window, I could see the values assigned to the object as below,
Name = Mike
Age = 23
Occupation = Student
On the Access database, I have a table called as UserTable which has columns called as ID, Name, Age, Occupation and now how do I pass the values from VBA to Access database.
I would want to add the value record by record and faster at the same time.
Here is where I am getting the error
strSQL = "PARAMETERS [Name] TEXT(255), [Age] INTEGER, [Occupation] TEXT(255);" _
& " INSERT INTO UserTable([User Name], [User Age], [User Occupation]);"
Please help me with this on my learning.
Create a reference to the ADO recordset library
create and open a Connection object to the access database
Dim Conn as new adodb.connection
conn.connectionstring = "google for connection string here"
conn.open
create a string holding an append query (watch out: you need commas between fields and ' around strings)
Dim strSQL as string
StrSql = "INSERT INTO [Usertable] ( Name, Age, Occupation ) "
strsql = strsql & "Values('" & me.Name & "'," & me.age & ",'" & me.occupation & "')"
Use EXECUTE to run this string
conn.execute strsql

VBA Insert Query: "Query input must contain at least one table or query""

I am importing data from an Excel spreadsheet into tblPOLinesTemp table, and then I have to apppend those to tblPOLines table. I am trying to execute an insert into SQL statement from VBA, but keep getting "Query input must contain at least one table or query" as error, and I cannot seem to figure out what is wrong as the SQL statement works when running it in Access! It is driving me crazy! Can you help?
My code (I have Dim'ed AppendPOlines as String):
AppendPOLines = "INSERT INTO tblPOlines ( PurchaseOrderID, PurchaseOrderLineID, [Material#], FirstDeliveryDate, Quantity, CreatedBy )" _
& "SELECT tblPOLinesTemp.PurchaseOrderID, tblPOLinesTemp.PurchaseOrderLineID, tblPOLinesTemp.[Material#], tblPOLinesTemp.FirstDeliveryDate, tblPOLinesTemp.Quantity, [TempVars]![VarUserID] AS CreatedBy" _
& "FROM tblPOLinesTemp LEFT JOIN tblPOlines ON (tblPOLinesTemp.PurchaseOrderLineID = tblPOlines.PurchaseOrderLineID) AND (tblPOLinesTemp.[PurchaseOrderID] = tblPOlines.[PurchaseOrderID])" _
& "WHERE (((tblPOlines.PurchaseOrderLineID) Is Null) AND ((tblPOlines.PurchaseOrderID) Is Null));"
CurrentDb.Execute AppendPOLines, dbFailOnError
Note that the Left Joins is to ensure that the Query does not insert rows with similar Purchase Order and Purchase Order Line ID - to avoid duplicate rows.
Thank you!
After and before each ["] put a blank space :
AppendPOLines = " INSERT INTO tblPOlines( PurchaseOrderID, PurchaseOrderLineID, [Material#], FirstDeliveryDate, Quantity, CreatedBy ) " _
& " SELECT tblPOLinesTemp.PurchaseOrderID, tblPOLinesTemp.PurchaseOrderLineID, tblPOLinesTemp.[Material#], tblPOLinesTemp.FirstDeliveryDate, tblPOLinesTemp.Quantity, [TempVars]![VarUserID] AS CreatedBy " _
& " FROM tblPOLinesTemp LEFT JOIN tblPOlines ON (tblPOLinesTemp.PurchaseOrderLineID = tblPOlines.PurchaseOrderLineID) AND (tblPOLinesTemp.[PurchaseOrderID] = tblPOlines.[PurchaseOrderID]) " _
& " WHERE (((tblPOlines.PurchaseOrderLineID) Is Null) AND ((tblPOlines.PurchaseOrderID) Is Null)); "
your query is executed like following:
INSERT INTO tblPOlines( PurchaseOrderID, PurchaseOrderLineID, [Material#], FirstDeliveryDate, Quantity, CreatedBy )SELECT tblPOLinesTemp.PurchaseOrderID, tblPOLinesTemp.PurchaseOrderLineID, tblPOLinesTemp.[Material#], tblPOLinesTemp.FirstDeliveryDate, tblPOLinesTemp.Quantity, [TempVars]![VarUserID] AS CreatedByFROM tblPOLinesTemp LEFT JOIN tblPOlines ON (tblPOLinesTemp.PurchaseOrderLineID = tblPOlines.PurchaseOrderLineID) AND (tblPOLinesTemp.[PurchaseOrderID] = tblPOlines.[PurchaseOrderID])WHERE (((tblPOlines.PurchaseOrderLineID) Is Null) AND ((tblPOlines.PurchaseOrderID) Is Null));
so CreatedByFrom is wrong and you get this error:
"query input must contain at least one table or query"

Visual Basic update column is doing arthmetic in query

I have a page that displays results in a SQL database. And then I have another page that lets me edit whichever row I want to edit. One of the fields are dates. If added into the database through one of my pages it gets put in with the format (YEAR-MN-DY)(2014-04-11). When I go to UPDATE the date it then does arithmetic on the date. For example. If the date is currently 2014-04-11 and I update/change the date to 2010-01-01 it will replace the date with "2008" which is 2010 -1 - 1.
The variable is a string that is received through a HTML form.
strSQL = "UPDATE sales SET cust_id = " & intcust_id & ", agent_id = " & intagent_id & ", saledate = " & strsaledate & " WHERE sale_id = " & intsale_id & ""
Is the SQL query I am running.
Also, the DATE is VARCHAR2 in the database and used as a string throughout my VB code. I kept it this way because not everyone enters the date the same and this is for simplicity.
The subtraction is occurring because the date is not being interpreted as a date, but as a number because it is missing its quotes.
Before
strSQL = "UPDATE sales SET cust_id = " & intcust_id & ", agent_id = " & intagent_id & ", saledate = " & strsaledate & " WHERE sale_id = " & intsale_id & ""
After
strSQL = "UPDATE sales SET cust_id = " & intcust_id & ", agent_id = " & intagent_id & ", saledate ='" & strsaledate & "' WHERE sale_id = " & intsale_id & ""
The answer from WorkSmarter tackles the problem. I think however you should not use string concatenation. It is wide open to sql-injections and it is indeed much nicer, simpler and less error prone to use parameters. Something like
strSQL = "UPDATE sales SET cust_id = #custid, agent_id = #agentid, saledate = #salesdate WHERE sale_id = #saleid"
set custid = cmd.CreateParameter("#custid", adChar,adInput,10, incust_id)
set agentid = cmd.CreateParameter("#cagentid", adInteger,adInput,0, ) ...
I'm asuming you have an ADODB.Command by the name of cmd. By doing it like this you are making your code a lot safer and, in my opinion, more readable since you don't have to worry about quotes and single quotes all the time. There is a clear distinction between the sql command and the params/values involved.
You can find good documentation on parameter on http://www.w3schools.com/asp/met_comm_createparameter.asp

String or binary data would be truncated. The statement has been terminated

I always got an error when adding a new data. the error says
String or binary data would be truncated. The statement has been terminated
As I've looked back on my backend or code. It looks like there's a conflict adding a TWO LABEL DATA in one column because I would like to join the (Year)-(StudentNumber)
Here's the code of my INSERT INTO Statement
INSERT INTO
[Student_Information] (StudentID, LastName, FirstName, MiddleName, Gender,
ContactNumber, Citizenship, Religion, Birthday, Address)
VALUES
( '" & lbl_cyear.Text - studid.Text & "','" + txt_lname.Text + "', '" + txt_fname.Text + "', '" + txt_mname.Text + "', '" + DDGender.Text + "', '" & txt_cnumber.Text & "', '" & txt_citizenship.Text & "' , '" + txt_religion.Text + "' , '" & txt_bday.Text & "', '" & txt_address.Text & "' )"
and here's the code how I generate the Year and the Student Number
Sub SNYear()
Dim test As Date
test = Convert.ToDateTime(Today)
lbl_cyear.Text = test.Year
End Sub
Sub SNGenerate()
'displaying Studentid
Dim SN As Integer ' Student Number
Dim SID As String 'Student ID Num as String
Dim rdr As SqlDataReader
cmd1.Connection = cn
cmd1.Connection.Open()
cmd1.CommandText = "Select Max (StudentID) as expr1 from [Student_Information]"
rdr = cmd1.ExecuteReader
If rdr.HasRows = True Then
rdr.Read()
End If
If rdr.Item(0).ToString = Nothing Then
SN = rdr.Item(0) + 1
SID = Format(SN, "0000")
ElseIf rdr.Item(0).ToString = 0 Then
SN = rdr.Item(0) + 1
SID = Format(SN, "0000")
Else
SN = rdr.Item(0) + 1
SID = Format(SN, "0000")
End If
studid.Text = SID
cmd1.Connection.Close()
End Sub
Can someone help me with the code? How to join 2 data in different label text and save it to one column in my table.
Woah! Never ever write sql queries like that. It's subject to dangerous SQL injection, and code like that is actually used as worst-case scenarios in SQL injection lectures everywhere!
That being said, the error message String or binary data would be truncated. The statement has been terminated. actually spells out what is wrong. You are trying to insert too much data into a field that has a specific dimension.
You are trying to insert the following expression into the StudentID field:
lbl_cyear.Text - studid.Text
I'm not even sure what you want to do there. Since Visual Basic is loosely typed by default, It will probably handle the lbl_cyear.Text as a number and try to subtract the studid.Text (as a number) from it. You probably mean something like this:
lbl_cyear.Text & "-" & studid.Text
It seems you are trying to use the StudentID column for two different types of information. Don't do that. Decide on one format for the student ids and dimension the column for it.
Is this a homework assignment?
Y#atornblad has some very valid points about re-structuring your code. However, the specific problem you are asking about is likely because you are trying to insert data into a column that is longer than the column can accept.
E.g. - you are trying to insert "Lorem Ipsum" into a column that has a maximum length of 5 characters.
Edit
You need to take another look at how your table is defined and make sure it is appropriate for the data you are storing. Also - make sure the data you are trying to store is in the correct format that the table was designed for. Don't assume it's in the format you want, actually step through the program in debug mode and look at what the variable is before it gets sent to the database.