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
Related
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)"
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
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)
My problem is likely all about date formatting in a SELECT.
In an asp file I open an ADO Recordset wanting to retrieve rows of a MS SQL table that fall between date1 (08/15/2013) and date2 (08/22/2013) (i.e., the previous 7 days from today's date.)
The SELECT does retrieve the appropriate 2013 rows but also retrieves rows going back to 08/15/2012.
Here is the SELECT:
oRS.Source = "SELECT * FROM aTable WHERE entry_Date BETWEEN '" & resultLowerDate & "' AND '" & resultCurrentDate & "' AND entry_Status <> 'INACTIVE'"
resultLowerDate = 08/15/2013 and resultCurrentDate = 08/22/2013.
The table is set up as follows with resultCurrentDate = "08/22/2013":
entry_Status entry_Date (varchar) LastName FirstName SELECT Result
INITIAL 08/15/2012 Smith Jim YES
INACTIVE 08/21/2012 Green Tom no
INITIAL 08/22/2013 Jones Mary yes
FOLLOWUP 08/22/2013 Jones Mary yes
FOLLOWUP 08/22/2013 Brown Sally yes
FOLLOWUP 08/22/2013 Smith Jim yes
Any thoughts as to why the INITIAL 08/15/2012 row gets selected along with the other rows that meet the SELECT query?
STOP STORING DATES IN VARCHAR COLUMNS! And STOP CONCATENATING STRINGS, USE PROPER PARAMETERS.
Sorry to yell, but we are getting multiple questions a day where people use the wrong data type for some unknown and probably silly reason, and these are the problems it leads to.
The problem here is that you are comparing strings. Try:
"... WHERE CONVERT(DATETIME, entry_date, 101)" & _
" >= CONVERT(DATETIME, '" & resultLowerDate & "', 101)" & _
" AND CONVERT(DATETIME, entry_date, 101)" & _
" < DATEADD(DAY, 1, CONVERT(DATETIME, '" & resultCurrentDate & "', 101))"
Or better yet, set resultLowerDate and resultUpperDate to YYYYMMDD format, then you can say:
"... WHERE CONVERT(DATETIME, entry_date, 101) >= '" & resultLowerDate & "'" & _
" AND CONVERT(DATETIME, entry_date, 101) < DATEADD(DAY, 1, '" & resultCurrentDate & "'"
Note that I use an open-ended range (>= and <) instead of BETWEEN, just in case some time slips into your VARCHAR column.
Also note that this query could fail because garbage got into your column. Which it can, because you chose the wrong data type. My real suggestion is to fix the table and use a DATE or DATETIME column.
The fact that your entry_Date column is a varchar field and not an actual date is the problem. If you cast it to a datetime during the select, you'll get the results you expect.
select *
from aTable
where cast(entry_Date as datetime) between '08/15/2013' and '08/22/2013'
Sql Fiddle link
I have a String variable in VB.NET and it contains a value like
"Date of 9/23/2012 Tot Sec_sale Amt = 29,22,696RM's Wise , Gunadeep=15,83,876 , Purushothaman C.S.=1,12,829 , P.madhusudhanreddy=4,63,933 , Sunil vakayil=6,31,120 , Girish Varghese=33,019 , Debarun Chakraborty=79,288 , Rajiv Varma=18,630, RM's DT Count 1,342"
In application side I am able to view this value. I stored this value in MySQL table column. That column contains a longtext datatype. But I am not able to view the full content. Not able to view the last part RM's DT Count 1,342. It shows like Rm's....
My table structure:
fld_msg longtext
fld_phone varchar(20)
fld_date date
fld_status varchar(45)
fld_type varchar(45)
fld_name varchar(50)
My VB.NET code:
Dim bh_msg As String =
"Date of " + Convert.ToDateTime(txt1.Text).Date +
" Tot Sec_sale Amt = " + strdmy_bh_sec_amt.ToString +
"RM's Wise " + bh_amt_frmt1.ToString + "," +
" RM's DT Count " + str_bh_dt_count.ToString
Most DB Viewer truncate long texts fields (blob, clob, ...) in order to maintain performances. But that's just debug view. The real data, and your program, should use the entire value.
Try to retrieve those values using your VB code. It should work