How do I create a table in SQL server with the default DateTime as empty, not 1900-01-01 00:00:00.000 that I get?
I mean, if there is no value inserted, the default value should be null, empty, etc.
if there is no value inserted, the default value should be null,empty
In the table definition, make this datetime column allows null, be not defining NOT NULL:
...
DateTimeColumn DateTime,
...
I HAVE ALLOWED NULL VARIABLES THOUGH.
Then , just insert NULL in this column:
INSERT INTO Table(name, datetimeColumn, ...)
VALUES('foo bar', NULL, ..);
Or, you can make use of the DEFAULT constaints:
...
DateTimeColumn DateTime DEFAULT NULL,
...
Then you can ignore it completely in the INSERT statement and it will be inserted withe the NULL value:
INSERT INTO Table(name, ...)
VALUES('foo bar', ..);
Even if your column is nullable, inserting an empty string will set the value to 1900-01-01 00:00:00.000. Make you insert real nulls not strings, then the db will store a null.
define it like your_field DATETIME NULL DEFAULT NULL
dont insert a blank string, insert a NULL INSERT INTO x(your_field)VALUES(NULL)
Ozi, when you create a new datetime object as in
datetime foo = new datetime();
foo is constructed with the time datetime.minvalue()
in building a parameterized query, you could check to see if the values entered are equal to datetime.minvalue()
-Just a side thought. seems you have things working.
I was having the same issue this morning. It appears that for a DATE or DATETIME field, an empty value cannot be inserted. I got around this by first checking for an empty value (mydate = "") and if it was empty setting mydate = "NULL" before insert.
The DATE and DATETIME fields don't behave in the same way as VARCHAR fields.
you can use like this:
string Log_In_Val = (Convert.ToString(attenObj.Log_In) == "" ? "Null" + "," : "'" + Convert.ToString(attenObj.Log_In) + "',");
Related
I am new to SQL Server here I am trying to insert date into the column which has DATETIME as datatype .
When I pass a datetime to the stored procedure from API it insert the values which I have passed. But If I pass an empty string " ", it inserts a default value of 1900-01-01 00:00:00.000. But I want to insert NULL if the data is " ".
I googled a lot but I can't find a solution for this .
#DATEVAL1 DATETIME = '',
#DATEVAL1 DATETIME = ''
INSERT INTO TABLE (mDate1, mDate2)
VALUES (#DATEVAL1, #DATEVAL2);
This is the code I have in my stored procedure.
When you set a datetime variable to an empty string an implicit conversion happens. And an empty string converts implicitly to 1900-01-01. Either just declare the variable and don't assign them a value or explicitly set them to NULL.
#DATEVAL1 DATETIME,
#DATEVAL2 DATETIME = NULL
Or you could use NULLIF. Since you are receiving these values from an API you would most likely have to use NULLIF. Otherwise a change to the API call would be required to send in a NULL instead of an empty string.
Values( NULLIF(#DATEVAL1, '')
Dates and strings are not the same thing. For some reason, SQL Server converts an empty string into the date value '1900-01-01 00:00:00.000' rather than generating an error.
My primary advice is to not use empty strings for dates. Instead, just use NULL:
DECLARE #DATEVAL1 DATETIME = NULL;
DECLARE #DATEVAL1 DATETIME = NULL;
INSERT INTO TABLE (mDate1, mDate2)
VALUES (#DATEVAL1, #DATEVAL2);
If for some reason you have to use empty strings, then you can use a trigger to convert the 1900 value to NULL or use NULLIF() in the INSERT:
INSERT INTO TABLE (mDate1, mDate2)
VALUES (NULLIF(#DATEVAL1, ''), NULLIF(#DATEVAL2, ''));
I will go on a different direction as the other two answers.
My guess is you have an APP with some dropdown combos or some text fields. Your APP call your API and then you send those values to the stored procedure. Sometimes the app send empty string and when you send those to the stored procedure are converted to 1900-01-01.
So if you have the following stored procedure:
CREATE PROCEDURE dbo.InsertDate
#DATEVAL1 DATETIME, #DATEVAL1 DATETIME
AS
INSERT INTO TABLE (mDate1, mDate2)
VALUES (#DATEVAL1, #DATEVAL2);
GO
In this case if you send '' to the stored procedure you will get 1900-01-01 at the moment the parameters are created because an implicit conversion occurs so NULLIF() won't work here.
You can add some IF () logic to the stored procedure to convert any 1900-01-01 to NULL before run the INSERT
Or you can add the logic to your API converting any '' to NULL before calling the stored procedure.
I have a column in my table called startdate. It is in string format. Most of the fields are 'NULL'. I am copying this column to another table which data type is 'Date'.
How can I convert all the values from string to Date in SQL.
I have tried this code:
INSERT INTO Destination_Table [new_date]
SELECT CONVERT(DATE,[startdate],103)
FROM Source_Table
nullif([startdate],'NULL') returns [startdate] unless it equals to 'NULL' and then it returns NULL (a real NULL, not the string 'NULL')
INSERT INTO Destination_Table [new_date]
SELECT CONVERT(DATE,nullif([startdate],'NULL'),103)
from Source_Table
For learning purposes, here are some expressions with the same results:
nullif(x,y)
case when x=y then null else x end
case x when y then null else x end
It looks like you are using MSSQL. If you are using MSSQL 2012, the following code should work :
INSERT INTO Destination_Table [new_date]
SELECT IIF([startdate] = "NULL", null, CONVERT(DATE,[startdate],103))
FROM Source_Table
What this does, is use the IIF() method to check the value of [startdate] and if the value is the text "NULL", then return the actual null value which can be allowed in most fields unless you have null disabled on the Destination_Table.[new_date] field.
Since the Date field can only accept and store Date/Time/Date&Time/(actual null) information, the text "NULL" is not valid.
Following is the equivalent for MySQL
INSERT INTO Destination_Table [new_date]
SELECT IF([startdate] == 'NULL', null, CONVERT(DATE,[startdate],103))
FROM Source_Table
(although I am unsure MySQL allows a conversion code as a param to CONVERT() )
I am pretty new in Microsoft SQL Server and I am not so into DB in general.
I have the following doubt about an insert query that begin in this way:
insert into MyTable DEFAULT VALUES
What exactly mean the DEFAULT VALUES specification?
Tnx
Andrea
Reading the fine manual yields:
DEFAULT VALUES
Forces the new row to contain the default values defined for each column.
Well it uses the default values specified in your table.
So for example if you have a column CreationDate datetime default(getdate()) it will use it.
If each of the required columns in MyTable has specified DEFAULT VALUE then this statement insert such a row.
For example you could have column Date with default 01/01/2014 and position with DEFAULT 'Developer' and this statement would insert such a record.
You can read more here: http://msdn.microsoft.com/en-us/library/aa933206%28SQL.80%29.aspx
You can watch default specifications in work by checking that code:
DECLARE #tmp as table
(
id int null,
num int null default(777),
txt varchar(10) null default('abc'),
date datetime null
)
insert into #tmp DEFAULT VALUES
select * from #tmp
Output is
id num txt date
NULL 777 abc NULL
I have a requirement to insert the literal value 'NULL' into a nvarchar column as a default value. But when I insert records the default is going as db NULL instead of the literal 'NULL'. Can someone tell me where I am going wrong?
So you want the actual string of "NULL" to be inserted? Try something like this:
create table NullTable
(
nvarchar(100) not null default 'NULL',
.... -- your other fields
)
EDIT: Here is a full solution
create table InsertNull
(
Nullfield nvarchar(100) not null default 'NULL',
someint int not null
)
go
insert into insertnull(someint)
select 20
select *
from InsertNull
Note the quotes:
INSERT INTO yourtable (varcharfield) VALUES ('NULL'); // string null
INSERT INTO yourtable (varcharfield) VALUES (NULL); // actual null
If set the default in code instead of the designer is should work.
ALTER TABLE [myTable] ADD DEFAULT ('NULL') FOR [TextColumn]
I have a sql server nvarchar field with a "Default Value or Binding" of empty string. It also happens to be a not null field.
Does this mean that there is no default or that it is a default of a string with no characters in it.
If I don't insert a value, will it insert with an empty string or fail with a "not null" error?
The default is a blank (empty) string.
If you don't provide a value, the insert will be successful and the value will be blank, not null.
Its the same as (assuming data is the col in question):
create table #t (id int, data varchar(100) not null default(''))
So:
insert into #t (id) values (1)
insert into #t (id,data) values (2,default)
insert into #t (id,data) values (3, 'allowed')
select * from #t
will return
1
2
3 allowed
and ..
insert into #t (id,data) values (1, null)
-- will error
If you have a true empty string as a default, then it will autopopulate with a 0 length string.
You should be careful to ensure it is a 0 length string and not nothing though. If for instance you are looking in the table builder gui for SSMS and it shows a blank for "Default Value or Binding", that means that there is no default value and an insert will fail if it is not populated. If you want it to have a 0 length string, populate it with '' (two single-quotes together with nothing in between.)
Default value for a column is just that - sql server will put that value when you dont supply one for the column. The value in the column will be an empty string. Not null error will not happen