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

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

Related

SQL INSERT with parameter as query

How can I insert parameter with value from database.
I have some field and I should insert value from this database + 1 (with plus one)
For example
myCommand.CommandText =
"INSERT INTO GAMES (GAME_NR, GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID) " &
" VALUES (#game_nr, #game_player_id, #game_nrontable, #game_role_id)"
'Example
myCommand.Parameters.Add("#game_nr", SqlDbType.Int).Value = **"(SELECT MAX(GAME_NR) FROM GAMES)" + 1**
You don't. You make GAME_NR and auto-incremented primary key:
create table games (
game_nr int auto_increment primary key,
. . .
);
Then you do the insert as:
INSERT INTO GAMES (GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID)
VALUES (#game_player_id, #game_nrontable, #game_role_id);
Let the database do the work.
You don't need the parameter, you can try following code.
myCommand.CommandText =
"INSERT INTO GAMES (GAME_NR, GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID) " &
" VALUES ((SELECT MAX(GAME_NR) + 1 FROM GAMES), #game_player_id, #game_nrontable, #game_role_id)"
But it looks like a primary key of the table. If Game_Nr is pr, You should use auto-inc. identity, then you don't need this param.
It will be.
myCommand.CommandText =
"INSERT INTO GAMES (GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID) " &
" VALUES (#game_player_id, #game_nrontable, #game_role_id)"

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

"Missing comma" error while inserting clob value in table

CREATE TABLE fcc_consistency_check
(
cons_id VARCHAR2(30),
cons_desc VARCHAR2(4000),
cons_query CLOB,
module_id VARCHAR2(2),
main_tab_name VARCHAR2(30),
hist_tab_name VARCHAR2(30),
col_name VARCHAR2(4000),
col_type VARCHAR2(4000),
check_reqd VARCHAR2(1)
);
INSERT INTO fcc_consistency_check
VALUES ('CHK_BC003','Missing records in contract_event_log','select a.CONTRACT_REF_NO ,a.Latest_Event_Seq_No,
c.PREV_WORKING_DAY from cstb_contract A ,sttm_dates c
where module_code = 'BC'
and c.Branch_code='000'
and not exists (select * from cstb_contract_event_log B
where a.contract_ref_no = b.contract_ref_no
and latest_event_seq_no = event_seq_no);',
'BC','BCCC_EVENT_LOG_MISREC','BCCC_EVENT_LOG_MISREC_HISTORY','CONTRACT_REF_NO,LATEST_EVENT_SEQ_NO,EOD_DATE','VARCHAR2(16),NUMBER,DATE','Y');
Not able to insert clob value, I'm getting this error
ORA-00917: missing comma
When I try to insert individual column value then I found that, error is throwing for column cons_query.
The problem is that you have quotes within your query:
'select a.CONTRACT_REF_NO
,a.Latest_Event_Seq_No,
c.PREV_WORKING_DAY from cstb_contract A ,sttm_dates
where module_code = 'BC'
^string starst here:
^ends here, there's a commma missing
However, the actual issue is not that a comma is missing but that you have quotes you forgot to escape. You need to write module_code = ''BC'' for example to escape those quotes (you have additional quotes in there, not just at 'BC').

Inserting values starting with zero in access database

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)