MS Access INSERT INTO statement - ms-access

I need to insert form data from my VB.NET application to a Microsoft Access database.
I am getting the error "Syntax error in INSERT INTO statement" when using the following syntax:
INSERT INTO bs1 (teacher, subject, date, period)
VALUES ('test', 'test', 'test', 'test')
I'll admit I'm used to the MySQL type syntax, any help on this matter would be greatly appreciated, thanks.

I believe date is a reserved word. You need to encapsulate the reserved field names in square brackets:
INSERT INTO bs1 (teacher, subject, [date], period) VALUES ('test', 'test', 'test', 'test')
EDIT: See the following article for a complete list of reserved words in Access 2002 and greater:
http://support.microsoft.com/kb/286335
~md5sum~

In Access the delimiter for literal values inserted into date fields is #, for text fields is ' or " and numeric field values do not have a delimiter, which suggests:
INSERT INTO bs1 (teacher, subject, [date], period)
VALUES ('test', 'test', #2009-12-31#, 0)

In Access Database Engine SQL code, when you need to specify that a literal value is of type DATETIME, you can either explicitly cast the value to DATETIME or use # characters to delimit the value.
Using an explicit cast using the CDATE() function:
INSERT INTO bs1 (teacher, subject, [date], period)
VALUES ('test', 'test', CDATE('2009-12-31 00:00:00'), 0);
Using a DATETIME literal value:
INSERT INTO bs1 (teacher, subject, [date], period)
VALUES ('test', 'test', #2009-12-31 00:00:00#, 0);
When INSERTing a value into a column of type DATETIME, if you do not specify an explicit DATETIME value, the engine will implicitly attempt to coerce a value to DATETIME. The literal value 'test' cannot be coerced to type DATETIME and this would appear to be the source of your syntax error.
Note: none of the above applies to the NULL value. In Access Database Engine SQL there is no way to cast the NULL value to an explicit type e.g.
SELECT CDATE(NULL)
generates an error, "Invalid use of NULL". Therefore, to specify a NULL DATETIME literal, simply use the NULL keyword.
It pays to remember that the Access Database Engine has but one temporal data type, being DATETIME (its synonyms are DATE, TIME, DATETIME, and TIMESTAMP). Even if you don't explicitly specify a time element, the resulting value will still have a time element, albeit an implicit one. Therefore, it is best to always be explicit and always include the time element when using DATETIME literal values.

Related

Insert a date in MySQL only if it is valid

I have a table with date values stored as strings, like '2012-01-15'. Some of them are invalid, like '2012-04-31'. I would like to insert the valid dates into a DATE type column in another table, and default the day to 1 if it is too large for the month.
DAYNAME seems to be the only function in MySQL that will check whether a date is valid. However, it issues a warning for an invalid date (in addition to returning NULL), which upgrades to an error in an INSERT or UPDATE statement.
So I'd like to do something like
INSERT INTO date_tbl (date_value)
SELECT IF(DAYNAME(date_string) IS NOT NULL, date_string, CONCAT(LEFT(date_string, 8), '1')
FROM date_string_table;
This fails with Data truncation: Incorrect datetime value: '2010-04-31' even though I am not actually inserting invalid data.
The problem with using INSERT IGNORE is running the risk of actually inserting invalid data, which I would really like to avoid.
EDIT Oct 5:
This problem can be reproduced without creating the intermediate table simply as
CREATE TABLE date_tbl (
date_val DATETIME
);
INSERT INTO date_tbl (date_val)
SELECT IF(DAYNAME('2012-04-31') IS NOT NULL, '2012-04-31', NULL);
I would like the above INSERT to insert NULL for that invalid date, instead of failing.
You can compare days of the proper date and last day for that month with LAST_DAY and STR_TO_DATE.
So your query would be:
INSERT INTO date_tbl (date_val)
SELECT IF(DAY(STR_TO_DATE('2012-02-30','%Y-%m-%d')) > DAY(LAST_DAY(STR_TO_DATE('2012-02-30','%Y-%m-%d'))), NULL,'2012-02-30');
DB Fiddle
A workaround is to use INSERT IGNORE and then validate after the fact:
SELECT date_value
FROM date_tbl
WHERE DAYNAME(date_value) IS NULL;
Should return zero rows.

SQL Error: 1364 - Field 'buys' doesn't have a default value

I am getting this error in mybb SQL table:
SQL Error: 1364 - Field 'buys' doesn't have a default value
Query: INSERT INTO mybb_bank_post ('pid','cost') VALUES ('1680','10000')
How can I resolve this?
This suggests that buys is declared NOT NULL. So, you need to assign it a value when you insert into the table:
INSERT INTO mybb_bank_post (pid, cost, buys)
VALUES (1680, 10000, 0);
Or, declare the table so buys is not NOT NULL -- that is NULL values are allowed. Or, provide a default value in the table definition.
Note: Do not use single quotes for column names or for numeric constants. Only use single quotes for strings and date constants.

MySql INSERT...ON DUPLICATE UPDATE with partial VALUES

I have a list of possibly-incomplete set of values that will be used to append to or update a MySql table using the INSERT...ON DUPLICATE KEY UPDATE construct. The requirements are as follows:
If an operation resolves to an INSERT and the field value IS supplied, use the value supplied;
If an operation resolves to an INSERT and the field value IS NOT supplied, use the field's table DEFAULT value;
If an operation resolves to an UPDATE and the field value IS supplied, use the value supplied;
If an operation resolves to an UPDATE and the field value IS NOT supplied, retain the current (table) field value.
I've come up with the following statement, but the clauses wrapped in ** are erroneous and I'm having difficulty expressing them:
INSERT INTO `test`
(`id`, `num`, `text`)
VALUES
('1', 100, 'aaa'),
('2', 200, DEFAULT),
('3', DEFAULT, 'ccc')
ON DUPLICATE KEY UPDATE
`num` = IF (**VALUES(`num`) = DEFAULT**, `num`, VALUES(`num`)),
`text` = IF (**VALUES(`text`) = DEFAULT**, `text`, VALUES(`text`));
Notes: id is the unique key. Both num and text have default (NOT NULL) values set.
Things I've tried, but aren't satisfactory:
Replacing DEFAULT in VALUES with NULL, and then test for, e.g., IF (VALUES (num) = NULL .... This works, but will insert NULL on INSERT (and generate a warning - e.g., "Column 'text' cannot be null"), which is not acceptable - I need to have the default value applied to the missing fields;
Using something like 'xxx' instead of DEFAULT for missing values, and testing for 'xxx' (STRCMP), but this will insert 'xxx' in case of INSERT;
I've not tried this as I can't find the command/proper syntax, but the idea is to test (in the IF clause) whether num and text in VALUES are literals (num or string) or a MySql keyword (i.e., DEFAULT) - possibly using regex? - and then act accordingly.
Of course, an alternative to the above might entail obtaining existing values from the database and/or hardcoding into the query the default values for the missing fields, but I trust the same result can be achieved more elegantly using a single MySql statement.
Thanks in advance for your feedback.

MYSQL: Insert a timestamp from a variable to a table

I have an INSERT query in ruby and I'm passing parameters from another table. One of the parameters is a timestamp value, for example: 2015-11-22 12:57:06 +0000 which is stored in a variable name created_at (of type Time)
insert into my_tbl set
name = '#{name}',
created_at = #{created_at}
and I'm always getting errors while trying to insert it.
I've tried to convert it to string, and to use str_to_date function, but the problem is that I have a timestamp value.
How can I insert the value to the table?
INSERT INTO my_tbl (name, created_at)
VALUES (name, created_at.to_s.split(' +').first)
Format the input in mysql from chat and from ruby program insert and format in this chat with the sale format
Update:
In mysql :
Select to_date('"+varchar+"','dd/mm/yyyy'......
In Ruby:
Varchar='01/12/2015"
Of course with format

MySQL date formats - difficulty Inserting a date

I am trying to further a question I asked yesterday where I wanted to know how to query a date in a different format. But now I am trying to do an insert using this method (see below) however I can't get it to work. I have checked the manual but it is not beginner friendly!
INSERT INTO custorder VALUES ('Kevin','yes'), STR_TO_DATE('1-01-2012', '%d-%m-%Y');
Put the date in single quotes and move the parenthesis (after the 'yes') to the end:
INSERT INTO custorder
VALUES ('Kevin', 'yes' , STR_TO_DATE('1-01-2012', '%d-%m-%Y') ) ;
^ ^
---parenthesis removed--| and added here ------|
But you can always use dates without STR_TO_DATE() function, just use the (Y-m-d) '20120101' or '2012-01-01' format. Check the MySQL docs: Date and Time Literals
INSERT INTO custorder
VALUES ('Kevin', 'yes', '2012-01-01') ;
Looks like you've not encapsulated your string properly. Try this:
INSERT INTO custorder VALUES ('Kevin','yes'), STR_TO_DATE('1-01-2012', '%d-%m-%Y');
Alternatively, you can do the following but it is not recommended. Make sure that you use STR_TO-DATE it is because when you are developing web applications you have to explicitly convert String to Date which is annoying. Use first One.
INSERT INTO custorder VALUES ('Kevin','yes'), '2012-01-01';
I'm not confident that the above SQL is valid, however, and you may want to move the date part into the brackets. If you can provide the exact error you're getting, I might be able to more directly help with the issue.
The date format for mysql insert query is YYYY-MM-DD
example:
INSERT INTO table_name (date_column) VALUE ('YYYY-MM-DD');
An add-on to the previous answers since I came across this concern:
If you really want to insert something like 24-May-2005 to your DATE column, you could do something like this:
INSERT INTO someTable(Empid,Date_Joined)
VALUES
('S710',STR_TO_DATE('24-May-2005', '%d-%M-%Y'));
In the above query please note that if it's May(ie: the month in letters) the format should be %M.
NOTE: I tried this with the latest MySQL version 8.0 and it works!
When using a string-typed variable in PHP containing a date, the variable must be enclosed in single quotes:
$NEW_DATE = '1997-07-15';
$sql = "INSERT INTO tbl (NEW_DATE, ...) VALUES ('$NEW_DATE', ...)";