Inserting values starting with zero in access database - ms-access

I have a field called Product_Id(type string), which has length of 7 and starting with 0. But while inserting through VBA into a table field of type text the zeros is not getting inserted.
This is the insert query:
dbs.Execute "INSERT INTO tablename (PROD_NBR)VALUES (" & prodID & ");"

I think I have fixed the error - you need to declare the value in single quotes.
The PROD_NBR is a string type and field in the table is text type, then the inserting variable should be declared inside single quotes then double quotes and between two & symbols:
dbs.Execute "INSERT INTO tablename (PROD_NBR)VALUES ('" & prodID & "');"

Responding to #Cherry's answer, the following method is less tedious than a parameterized query, aka prepared statement. prodID can safely contain quotes and other special characters.
With dbs.OpenRecordset("tablename")
.AddNew
.Fields("PROD_NBR") = prodID
.Update
End With
Regarding the "starting with zero" part of your question, do you want PROD_NBR to always be 7 characters, padded with leading 0's? Then replace prodID with:
Right("0000000" & prodID, 7)

Related

Dsum with Null Value

I am having abit of a situation and hope you can point me at the right direction.
1st DSUM (Text2):
=DSum("[quantity_ya7]","Stock","[part_number]= '" & [part_number] & "'")
2nd DSUM (Text2): (This can be Null at times as there are no withdrawals or records)
=DSum("[amt_ya7]","Withdrawal","[part_number]= '" & [part_number] & "' ")
After setting the 2 DSUM above, I will carry the subtract out.
=Text1-Text2
If there are values for to calculate for 2nd DSUM, the result will display in order. Else, it will be empty. (No values displayed)
How do I calculate as -0 (deduct 0) so I can get the right value displayed?
Thank you, much appreciated.
You can use the Nz function to return zero, a zero-length string ("
"), or another specified value when a Variant is Null. For example,
you can use this function to convert a Null value to another value and
prevent it from propagating through an expression.
https://support.office.com/en-gb/article/Nz-Function-8ef85549-cc9c-438b-860a-7fd9f4c69b6c
In your case you want the DSUM to return 0 rather than Null when there's no value so you can use it in a calculation.
=NZ(DSum("[amt_ya7]","Withdrawal","[part_number]= '" & [part_number] & "' "),0)

Split Delimited Field To Multi Fields

I have an access 2013 table that houses one field with comma separated values. I have created a second table that I need to parse the results into with a structure like so
uPPID number
value1 short text
value2 short text
value3 short text
value4 short text
I am dynamically creating the table so it will always have enough "value" fields to accommodate for the number that will be parsed out. Sample data is like such:
uppID values
aeo031 boat, goat, hoat, moat
And I would want the field mappings to go like such
uPPID = aeo031
value1 = boat
value2 = goat
value3 = hoat
value4 = moat
How can access vba parse out a csv list from one field to many?
There are probably faster/better solutions than the follwing VBA loop that inserts records one by one in the destination table. But for instance it does the job.
TableCSV is the name of the source table
TableFields is the name of the destination table
The constant maxValues specifies the number of fields values available
The query composes dynamically the INSERT INTO statement after composing the values fields; it completes it to provide all the columns, and adds the surrounding quotes '...'. (p.s. it could be simplified if we can insert without specifying all column values..)
.
Sub splitTable()
Const maxValues As Long = 4 ' <-- Set to number of value fields in destination table
Dim query As String, values As String, rs
Set rs = CurrentDb.OpenRecordset("TableCSV")
Do Until rs.EOF
values = rs!values ' next we add commas to provide all fields
values = values & String(maxValues - UBound(Split(values, ",")) - 1, ",")
values = "'" & Replace(values, ",", "','") & "'" ' 'a', 'b', '', '' etc
query = "INSERT INTO TableFields VALUES (" & rs!uPPID & "," & values & ")"
Debug.Print query
CurrentDb.Execute query
rs.moveNext
Loop
End Sub

Mysql query not inserting values

I am trying to use the query below to insert a concatenated converted set of integers to string for use on a datetime field in my table.
TABLE
Field Type
empID int(11)
time_stamp datetime
in_out char(3)
am_pm char(2)
QUERY
Dim query As String = "INSERT INTO attendance VALUES(" & empID.Text & _
"STR_TO_DATE(CONCAT("& empYear.Text & ",'-'," & empMonth.Text & ",'-'," & _
empDay.Text & ",' '," & empHour.Text & ",':'," & empMin.Text & ",':'," & _
empSec.Text & ",'%Y-%m-%d %H:%i:%s'),'out','pm')"
There is no problem with the connection and the values. I have tried to insert the values into a test column of string type and the output is this:
133201712311827
I am pretty sure it's with how I use these characters: '' "" "," - :. I just can't figure out how.
First problem I see, here
& empID.Text & "STR_TO_DATE(. . . .
you're missing comma after first value
& empID.Text & "***,*** STR_TO_DATE(. . . .
Second issue, I identified when I've replaced your text values with hard coded values - You are missing closing parenthesis for str_to_date. Here ,'%Y-%m-%d... should be ), '%Y-%m-%d...
STR_TO_DATE(CONCAT(1999,'-',01,'-',01,' ',10,':',25,':',30***)***,'%Y-%m-%d %H:%i:%s')
As you see- my replacement shows that you have no issues with concatenation, single quote and :. Theo only other variable here is quality of data in text boxes.
Update
This answer (above) is correct. Using sql fiddle I created schema and when replaced text box values with hard-coded ones - all worked. My suggestions to add comma and parenthesis hold true. Your claim about problems with single quotes are false.
create table xxx (empID int(11), time_stamp datetime, in_out char(3), am_pm char(2));
INSERT INTO xxx VALUES(123,
STR_TO_DATE(CONCAT('2017','-','1','-','23',' ','10',':','35',':','40'),'%Y-%m-%d %H:%i:%s'),
'out','pm');
commit;
Select * from xxx
empID | time_stamp | in_out | am_pm
123 | January, 23 2017 10:35:40 | out | pm
End Update
On top of that, you could do it much better by parameterizing, which will look like something like this
command.CommandText = "insert into ... values (#1, #2, #3, #4)"
command.Parameters.AddWithValue("#1", Convert.ToInt32(empID.Text))
dim date as new DateTime(Convert.ToInt32(empYear.Text), Convert.ToInt32(empMonth.Text), . . . . )
command.Parameters.AddWithValue("#2", date)
. . . . . .
command.ExecuteNonQuery()
Parameterizing will make it easy to work with dates and strings

Removing white spaces in sql field

I have a table with three fields (ID , machine_name, carpark_id) two of the machine names has (311A__) _ =spaces and (311B__) how to select and insert rows into machine name which have spaces in it.
sql_local = """SELECT id FROM customer_1.pay_machines WHERE machine_name="%s" """ % machine
sql_local = """INSERT INTO customer_1.pay_machines (machine_name, carpark_id) VALUES ("%s", 0)""" % machine
sql_local = """SELECT id FROM customer_1.pay_machines WHERE machine_name="%s" """ % machine
sql_local = """INSERT INTO customer_1.pay_and_display (plate, machine_id, ticket_datetime, expiry_datetime, ticket_name, ticket_price) VALUES ("%s", "%s", "%s", "%s", "%s", "%s") """ % (plate, machineId, entryDatetime, expiryDatetime, ticketName, ticketPrice)
I know what problem you are having!
MySQL always auto-trims your string, so inserting 'a ' will actually be just 'a'.
https://dev.mysql.com/doc/refman/5.0/en/char.html
"For VARCHAR columns, trailing spaces in excess of the column length are truncated prior to insertion and a warning is generated, regardless of the SQL mode in use. For CHAR columns, truncation of excess trailing spaces from inserted values is performed silently regardless of the SQL mode."
You can try using a blob, which will not ignore whitespaces
If you want to continue to use CHAR or VARCHAR fields, you can use LIKE 'String ' to include whitespaces, WHERE col = 'String ' will not work
Filtering machine with space: where machine like '% %';
Insert: What is the problem? Just put the name with the space between the single quotes.
I notice you are using double quotes instead of single quote, the usual string delimiter in MySQL.

Wrap Insert Statement in single quotes MS Access, setting default vlaues

I have a insert statement in MS Access which needs to be wrapped in single quotes so that it can be passed as string to a column in another table. here is my insert statement below
Insert into Employee(EmpName,EmpDepartment) Values ('Mike',NULL)
when I wrap I am getting errors arounf 'Mike'
'Insert into Employee(EmpName,EmpDepartment) Values ('Mike',NULL)'
Below is my create table with two primary keys
create table Employee([OBJECTID] AUTOINCREMENT(1, 1), EmpName Text(10), EmpDepartment Text(50), Primary Key (OBJECTID, EmpName))
How can I set default values to EmpName as Mike and Null to EmpDepartment while creating table it self ??
You will need ADO to create a default easily with a standard SQL mode for Access. This will run in VBA.
sSQL = "create table Employee([OBJECTID] AUTOINCREMENT(1, 1), " _
& "EmpName Text(10) default mike, EmpDepartment Text(50), " _
& "Primary Key (OBJECTID, EmpName))"
CurrentProject.Connection.Execute sSQL