SQL Server 2008 Datetime field overflow - c#

I am using C# to interface with a SQL database. the database has a DateTime field. When I try to write a DateTime object from C#, I get the following error:
ERROR [22008] [Microsoft][ODBC SQL Server Driver]Datetime field overflow
I found this on the topic:
http://social.msdn.microsoft.com/forums/en-US/sqldataaccess/thread/ac1b5a6d-5e64-4603-9c92-b75ba4e51bf2/
Is there any manipulation I can do to my DateTime object on the C# side?
EDITS
I am trying to add DateTime.MinValue

Sounds like you are just passing in a bad date. For example, DateTime.MinValue is outside the accepted range for SQL Server datetime values by about 1600 years.
By the way, you shouldn't be using ODBC for C# to SQL Server communication. Using System.Data.SqlClient will give you much better performance.

The .NET DateTime object has a bigger range than the SQL date/time field.
In your data access layer, anytime your writing a date to the database, ensure that is inside the rate of SqlDateTime.MinValue and SqlDateTime.MaxValue.

I'm quiet sure, your .NET DateTime is not initialized, what means it is "0000-01-01" and this is not a valid value for SQL Server DATETIME and often not a desired value ;-)

Change all your datetime columns to datetime2 type. Generate the sql scripts using the query below.
select distinct concat('alter table ', table_name, ' alter column ', column_name, ' datetime2 ',
case when(is_nullable = 'NO') then ' NOT ' else '' end, ' NULL;')
from information_schema.columns where data_type = 'datetime';

Related

what is insert value pattern for datetime field [duplicate]

I want to insert a datetime value into a table (SQL Server) using the SQL query below
insert into table1(approvaldate)values(18-06-12 10:34:09 AM);
But I get this Error msg:
Incorrect syntax near '10'.
I tried it with the quotes
insert into table1(approvaldate)values('18-06-12 10:34:09 AM');
I get this error message
Cannot convert varchar to datetime
You will want to use the YYYYMMDD for unambiguous date determination in SQL Server.
insert into table1(approvaldate)values('20120618 10:34:09 AM');
If you are married to the dd-mm-yy hh:mm:ss xm format, you will need to use CONVERT with the specific style.
insert into table1 (approvaldate)
values (convert(datetime,'18-06-12 10:34:09 PM',5));
5 here is the style for Italian dates. Well, not just Italians, but that's the culture it's attributed to in Books Online.
A more language-independent choice for string literals is the international standard ISO 8601 format "YYYY-MM-DDThh:mm:ss". I used the SQL query below to test the format, and it does indeed work in all SQL languages in sys.syslanguages:
declare #sql nvarchar(4000)
declare #LangID smallint
declare #Alias sysname
declare #MaxLangID smallint
select #MaxLangID = max(langid) from sys.syslanguages
set #LangID = 0
while #LangID <= #MaxLangID
begin
select #Alias = alias
from sys.syslanguages
where langid = #LangID
if #Alias is not null
begin
begin try
set #sql = N'declare #TestLang table (langdate datetime)
set language ''' + #alias + N''';
insert into #TestLang (langdate)
values (''2012-06-18T10:34:09'')'
print 'Testing ' + #Alias
exec sp_executesql #sql
end try
begin catch
print 'Error in language ' + #Alias
print ERROR_MESSAGE()
end catch
end
select #LangID = min(langid)
from sys.syslanguages
where langid > #LangID
end
According to the String Literal Date and Time Formats section in Microsoft TechNet, the standard ANSI Standard SQL date format "YYYY-MM-DD hh:mm:ss" is supposed to be "multi-language". However, using the same query, the ANSI format does not work in all SQL languages.
For example, in Danish, you will many errors like the following:
Error in language Danish
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
If you want to build a query in C# to run on SQL Server, and you need to pass a date in the ISO 8601 format, use the Sortable "s" format specifier:
string.Format("select convert(datetime2, '{0:s}'", DateTime.Now);
Management studio creates scripts like:
insert table1 (foodate) values(CAST(N'2012-06-18 10:34:09.000' AS DateTime))
you need to add it like
insert into table1(date1) values('12-mar-2013');
No need to use convert. Simply list it as a quoted date in ISO 8601 format.
Like so:
select * from table1 where somedate between '2000/01/01' and '2099/12/31'
The separator needs to be a / and it needs to be surrounded by single ' quotes.
If you are storing values via any programming language
Here is an example in C#
To store date you have to convert it first and then store it
insert table1 (foodate)
values (FooDate.ToString("MM/dd/yyyy"));
FooDate is datetime variable which contains your date in your format.
I encounter into a more generic problem: getting different (and not necessarily known) datetime formats and insert them into datetime column. I've solved it using this statement, which was finally became a scalar function (relevant for ODBC canonical, american, ANSI and british\franch date style - can be expanded):
insert into <tableName>(<dateTime column>) values(coalesce
(TRY_CONVERT(datetime, <DateString, 121), TRY_CONVERT(datetime, <DateString>,
101), TRY_CONVERT(datetime, <DateString>, 102), TRY_CONVERT(datetime,
<DateString>, 103)))
If the format of the date is as follows in sql : (datetime,null)
1
You can also use the "CAST" keyword
(CAST('2015-12-25 15:32:06.427' AS DateTime))
Just make sure that the date is in the correct format

.Net DateTime cannot be saved to SQL Server DATETIME because of precision

I have a property on an class that is of the .Net type DateTime. It is attempting to save into a table in SQL Server 2008 with a type of DATETIME. I am receiving a Database Error when I attempt to save a new record to the table from my .Net service.
When I look at SQL Server Profiler and see the call to the Stored Procedure that saves to the table, the property is a string: '2014-09-04 23:08:18.0500000'. When I truncate this string to just milliseconds the Stored Procedure call succeeds. The conversion of my .Net DateTime property to this string all happens under the hood and I have no control over that.
I do not need the full precision that I am seeing in the string, but it is important to keep milliseconds. I would rather not change my table column to a data type of DATETIME2. How can I remove the extra precision from the .Net DateTime property?
DateTime dateTime;
dateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
Please have #Tanner reply and mark that as an answer if correct as I believe he is correct in his comment above. Be careful to check for NULL on DateTime as you cannot convert to formated string if no data exists.
Below explains the range of DATETIME field in SQL Server.
http://msdn.microsoft.com/en-us/library/ms187819.aspx

Fetching date in SQL Server 2008

How to split date in select query of SQL Server 2008 ?
If you feed you feed current date in database and the type of that column in database is date time then It will store the date as well as time.If any one want to fetch only the date part from that column then what can he do.
I can use this query but it should not work.
SELECT DonorName, DATE(DateOfDonation) AS DateOfDonation
FROM CreateDonorDetail;
it give error-
'DATE' is not a recognized built-in function name.
SQL Server 2008 has a DATE datatype - but it's disabled if your database was upgraded from a SQL Server 2005, and you didn't change the database compatibility level.
Check your compatibility level like this:
SELECT name, compatibility_level
FROM sys.databases
WHERE name = '-Your-database-name-here-'
If this compatibility level is 90, it's set to SQL Server 2005 and you won't be able to use DATE. Update your compatibility level to 100:
ALTER DATABASE AdventureWorks2012
SET COMPATIBILITY_LEVEL = 100
Now you should be able to use DATE:
SELECT
DonorName,
CAST(DateOfDonation AS DATE) AS DateOfDonation
FROM CreateDonorDetail;
Cast as Date type:
SELECT DonorName, Cast(DateOfDonation as Date) AS DateOfDonation
FROM CreateDonorDetail;
Prior to SQL Server 2008 you colud use something like this:
SELECT DonorName, CAST(FLOOR(CAST(DateOfDonation AS FLOAT)) AS datetime) AS DateOfDonation FROM CreateDonorDetail
DECLARE #DateTime DATETIME
SELECT #DateTime = '2010/05/20 11:21:13'
SELECT CONVERT(VARCHAR(10),#DateTime ,105) AS Date
the result will be in dd-mm-yyyy format (105)
Hope it will helps
mark as answer if it helped

Query a datetime in SQL Server 2005 Express

How to query the rows based on DateTime in SQL Server 2005 Express installed on windows server 2008 r2?
I have code that selects rows based on from and to date values. It's working in my Windows 7 system . But, It's not working on Windows Server 2008 R2 ... Any help
this.filterreportTableAdapter.FillBy(this.cRdataset.filterreport_datatable, fromdate, todate);
and my SQL query is
SELECT *
FROM tablename
WHERE DATE BETWEEN #fromdate and #todate
It sounds like date/time values are being passed as strings. This is always a bad idea, and formatting issues abound. The best approach here is simply: use correctly-typed parameters. if both client and server know it is a DateTime, then it is passed as a primitive vaue, not a string - thus no formatting problems.
Make sure that fromdate and todate in the c# are DateTime, and that #fromdate, #todate and tablename.DATE in the TSQL are datetime.
Please set the datetime format same as the one on your windows 7 e.g. : dd/MM/yyyy
it seems that you have a date format mistake when passing date parameters.
there are two solutions:
first, you can try to use date format that works everywhere that is:
YYYYMMDD ex : 20120722.
another solution is to make a DateDiff in sql query
Best regard

How to convert SQL Server timestamp object to string

I need your help in small problem, I have a column (data type timestamp) in SQL Server 2008.
Now I want to show this timestamp value in ASP.Net C# app as string. Is there any way to do that?
I tried it using regular data fetching in ASP.Net but it produced System.byte[] as output rather than actual value. In SQL Server Management Studio values are represented as 0x000000000000B3C0.
One option is to change it to the Date, while getting from the database. Like:
SELECT timestamp = DATEDIFF(s, '19700101', yourTimestampColumn)
FROM yourTable
I don't know if i catch you, but in sql you can cast timestamp value to datetime then to varchar like this:
declare #val timestamp = 0x0000AAE200B29565
select cast(cast(#val as datetime) as varchar(max))

Categories

Resources