Inserting datetime value into sql server table column - sql-server-2008

I'm attempting to insert a datetime('2013-08-30 19:05:00') value into a SQL server database table column(smalldatetime) and the value stays "NULL" after the insert.
I'm doing this to 6 other columns that are the exact same type. What is this only occuring on one column? I've triple checked that the names of the columns are correct. Any ideas?

Assuming the situation is as you describe
CREATE TABLE T
(
S SMALLDATETIME NULL
)
INSERT INTO T
VALUES('2013-08-30 19:05:00')
SELECT *
FROM T /*Returns NULL*/
There are only two ways I can think of that this can happen.
1) That is an ambiguous datetime format. Under the wrong session options this won't cast correctly and if you have some additional options OFF it will return NULL rather than raise an error (e.g.)
SET LANGUAGE Italian;
SET ansi_warnings OFF;
SET arithabort OFF;
INSERT INTO T
VALUES('2013-08-30 19:05:00')
SELECT *
FROM T /*NULL inserted*/
2) You may have missed the column out in an INSTEAD OF trigger, or have an AFTER trigger that actually sets the value back to NULL.

Related

set default value to field if empty string is inserted through query

So I have table A which contains a column Z with default value set to string "diverse".
The queries come in from a php script which takes the data from a jqueryAJAX post request.
I would like to have my DB set the respective field of column Z to default value if the query received an empty string for insertion into/update of this column.
I really would like to accomplish this using mysql functionality, without using any more custom coded php logic.
I already read about using WHEN/THEN logic here:
Set default value if empty string is passed MySQL
and here
MySQL update CASE WHEN/THEN/ELSE
but these don't explain how I permanently configure a table/column in a way that it exposes this "default" behavior not just on receiving a NULL value, but also on receiving an empty string.
Besides:
If I set a column to NOT NULL and also add a default value for the column, would the query just fail if I tried to insert a/update to a NULL value, or would the DB instead flip to the default value?
MySQL/MariaDB will put the value to a column you specify in the insert/update-statement. If you do not provide a value, the default (if specified) will be used.
If you want to use the default value even if the insert/update-statement does provide a value (NULL / empty string), you will have to have the logic somewhere. The options are that you put the logic in your application code (PHP) or if you want to do it in MySQL/MariaDB, you can use a trigger to check the new value and act accordingly.
CREATE TRIGGER ins_A BEFORE INSERT ON A
FOR EACH ROW
BEGIN
IF NEW.Z is null or NEW.Z='' THEN
SET NEW.Z = 'diverse';
END IF;
END;
And do the same for UPDATE
Please follow 2 case bellow:
create table Test
(
a varchar(400) not null default 'test',
b varchar(10)
)
collate = utf8mb4_unicode_ci;
Case 1:
INSERT INTO Test (a, b) VALUES (NULL, 'case1');
=> resul: error because column a required not null;
Case 2:
INSERT INTO Test (b) VALUES ('case1');
=> OK, and result of column a = defaul value = test

Set default value to all columns in a database

I am working in a PHP + MySQL application. The application is working fine for me. But when I hosted it in another server, I got a MySQL error:
Error Code: 1364. Field 'field' doesn't have a default value
I know this is a problem with the MySQL version and we should setup default values for all columns. But currently I have more than 100 tables. So I need to set default value to NULL for all columns in all tables that has no default value yet.
I can't make use of the strict mode option, because the server is a shared one. Is it possible to setup in a single step rather than setting for each and every table ? If not possible tell me the easiest way to setup it.
Any help would be greatly appreciated
For anyone else with this problem, it will take a bit of coding to perform automatically, but the following would be how you would do so:
First run the following query:
SELECT table_schema,table_name,column_name,data_type FROM information_schema.columns WHERE IS_NULLABLE='NO' AND column_default is null AND column_key=''
Next, for each row returned from the above query perform the following:
If data_type contains 'int' set default to 0
else if data_type='datetime' set default to '0000-00-00 00:00:00'
else if data_type='date' set default to '0000-00-00'
else if data_type='time' set default to '00:00:00'
else set default to ''
create and run the following query with all [[...]] variables replaced with their proper values:
ALTER TABLE `[[table_schema]]`.`[[table_name]]` ALTER COLUMN `[[column_name]]` SET DEFAULT '[[default]]'
This should replace the default values for all databases, all tables, all columns that are set to be NOT NULL and are not primary keys and have no default value set.
Another solution that i found is like:-
Get all column name put it in array...
Now push values in column array for inserting -- with ZERO value for all those arrays we do not have values.
FOR EXAMPLE:
in a table we have COLUMN
NAME LASTNAME COMPNAME PHONO EMAIL ADDRESS ALTERPERSON ALTERPHONE ALTEREMAIL
Now after migration we see the eeror
Error Code: 1364. Field 'field' doesn't have a default value
if we run a INSERT QUERY LIKE
mysqli_query($con,'insert into table
(NAME,LASTNAME,COMPNAME,PHONO,EMAIL,ADDRESS) values
(NAME,LASTNAME,COMPNAME,PHONO,EMAIL,ADDRESS)')
now it will give error...
So just turn the table
get all the column value from DB.TABLE
put it in an array or do it like one by one using while loop or for loop....
check insert values for each column
put condition if insert value is equal to ZERO or NULL then insert ZERO it will solve all issues.
WHY ZERO --
because it will work for VARCHAR,TEXT,INT,BIGINT and in many Data Types except time or date function and DATE/TIME data type got ZERO values by default...
=============================== Another option...
run a PHP code
get all TABLE NAME
then for each TABLE NAME
get all COLUMN NAME
and run this command as in function under loop
ALTER TABLE DB.TABLEnAME CHANGE columnNAME_A columnNAME_A
VARCHAR(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL
DEFAULT NULL;
=======================
And its DONE

Can I specify a query as a field's default value?

I mean something like:
create table Measures (
id_user int,
date timestamp,
measure_1 double default 'select measure_1 from Measures where data = '**/**/****'',
measure_2 double default 'select measure_1 from Measures where data = '**/**/****'');
In this way I insert the value of the last measure saved in the db..
Is it possible?
Not directly:
11.7 Data Type Default Values
... the default value must be a constant; it cannot be a function or an expression.
You'll have to do this on application level, or in a trigger as suggested by #Timekiller.
You can do that via a before-insert trigger.
Check if NEW.measure_1 is null, and if it is, then perform select and store results.
UPD:
Right, I was in a bit of a hurry yesterday, and forgot to give an example later. Trigger is a good replacement for complex default value - it will work transparently, will look just like the default value from database user standpoint, and you won't have to do anything on the application level, since triggers are stored in the database itself. It will look something like this:
CREATE TRIGGER `measures_bi_trigger` BEFORE INSERT ON `Measures`
FOR EACH ROW BEGIN
if NEW.measure_1 is null then
SET NEW.measure_1 = (select measure_1 from Measures where ... limit 1);
end if;
if NEW.measure_2 is null then
SET NEW.measure_2 = (select measure_2 from Measures where ... limit 1);
end if;
END
It's not exactly clear what should be in your where condition, so you'll have to substitute ... yourself. Note that your query should return exactly one row, so either use an aggregate function like MAX or order by ... limit 1. If your query returns no rows, NULL will be inserted.

Fetch timestamps as integers in MySQL by default

How do you set in MySQL the timestamp type column to be returned as integer by default?
To specify:
I know that I can query
select UNIX_TIMESTAMP(timestamp_column) from table ...,
but when I query
select * from table ...
How can I force timestamp_column to be returned as int, and not as YYYY-MM-DD HH:ii:ss, in every query like the previous one?
Is there a query like set names utf8 that I can execute to make the described behaviour default?

How do I prevent NULLs from being inserted in MySql when using user variables?

I am struggling to find a way to get MySql to use user variables properly in an insert statement. MySql is inserting NULL where I have my variable. Here is a portion of my installation script:
SELECT CONCAT("env=",#env); //this is irrelevant debugging
SET #OV_PRIMARY_PORT = CASE #env
WHEN 'agile' THEN '443'
WHEN 'fit' THEN '443'
WHEN 'pilot' THEN '443'
WHEN 'production' THEN '443'
END
;
// this is irrelevant debugging
SELECT CONCAT("OV_PRIMARY_PORT=",#OV_PRIMARY_PORT);
INSERT INTO IsensorDefaultConfigItem
(item_name, application_name, application_component, initialized_time, item_value)
VALUES ('bubba', 'bubba', 'bubba-primary4', NOW(), #OV_PRIMIRY_PORT);
The variable #env was set in a previous part of the script and the SELECT statement is there only to display the value for me to confirm that is working. The same is true of the SELECT that contains #OV_PRIMARY_PORT....it is just there for debugging.
Always - both selects show that the variables are set as I would have expected.
Always - I get NULL inserted into my table for the item_value column.
That column is defined as a TEXT column that does default to NULL.