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
Related
I am working on a website in asp.net. I am getting a date from a web page and then depending on the user input I want to get results from SQL Server database (using stored procedures).
Problem is that I am getting date only from UI in this format 2016-10-08 which is of type string. But in the database, I have a column which is of type datetime in this format 2016-10-08 17:38:00.000.
I am using this query to search but it does not work.
select *
from table
where acceptedDate like #sDate+ '%';
where sDate is input parameter for stored procedure. Please help. thanks
Don't pass dates as strings. Pass them as DateTime.
The .Net DateTime maps directly to SQL Server's DateTime. All you have to do is parse the string to a DateTime struct in your .Net code and pass it as a parameter to your stored procedure.
To search for a specific date and ignore the Time portion of the DateTime, better use >= and < in your sql:
select *
from table
where acceptedDate >= #Date
AND acceptedDate < DATEADD(DAY, 1, #Date);
If you only want compare with day level and ignoring the hours part, you can use DateDiff function.
Pass d or DAY to interval parameter of DateDiff
For example:
DECLARE #sDate VARCHAR(100)='2016-10-08'
IF ISDATE(#sDate)=1
BEGIN
select *
from table
where datediff(d,acceptedDate,#sDate)=0 --same day
END
ELSE
PRINT 'Invalid date format!'
I have a column in my SQL Server database of nvarchar datatype, and I store dates with ####/##/## format in it. With my mistake some of dates store with ##/##/#### format.
How can I modify all dates in my database to format ####,##,##?
Example: 01/01/2016 to 2016/01/01
Use CONVERT function. Write simple SQL query:
UPDATE YourTable
-- get Date from nvarchar and format to yyyy/mm/dd
SET DateColumn = CONVERT(nvarchar,CONVERT(DATE, DateColumn, 103), 111)
-- only in rows that can be parsed from dd/mm/yyyy format
WHERE TRY_CONVERT(DATE, DateColumn, 103) IS NOT NULL
103 - dd/mm/yyyy format. 111 - yyyy/mm/dd format. check this article
But actually you really should store your dates in DATE type column not in NVARCHAR.
I have existing datatables that include a field of hexadecimal data which is actually a date.
From existing code, I know that data is converted to a DATETIME values with:
SELECT CAST(0x0000214900000000 AS DATETIME)
My problem now is that I need to insert values into such fields manually, but I don't know how to generate the hexadecimal value for a given DATETIME.
I have tried to insert AS BINARY(8) but that does not return the correct value like above.
How do I perform this conversion?
If you are doing this ALL in SQL here is a simple example that exists all in memory. You can run this as is in SQL Management Studio and the syntax should be fine for 2008 SQL Server and up.
DECLARE
#Date DateTime = getdate()
, #Hex varbinary(8)
;
DECLARE #Temp TABLE ( value varbinary(8) );
INSERT INTO #Temp VALUES (0x0000214900000000),(cast(#Date AS varbinary));
Select
value
, cast(value AS DateTime)
from #Temp
SELECT #Hex = cast(cast('2015-04-01' AS DateTime) AS varbinary)
INSERT INTO #Temp VALUES (#Hex)
Select
value
, cast(value AS DateTime)
from #Temp
You basically 'cast' an object type to a different object. Yet for varbinary if you are storing this you need to specify a length as well. You can cast back and forth in SQL quite easily if the type conversion is allowed. If you wanted to do this for insertion from .NET code directly that may be slightly different.
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';
I serialize my c# object to xml, then got varchar such as '2009-05-09T13:50:59.6361485+08:00'.
But SQL Server return following messgae: 'Result: Msg 241: Conversion failed when converting date and/or time -- from character string.'
after I execute following sql:
declare #msg xml
set #msg='<root><date>2009-05-09T13:50:59.6361485+08:00</date></root>'
select #msg.value(N'(//root/date/text())[1]','datetime')
Try this:
declare #msg xml
set #msg='<root><date>2009-05-09T13:50:59.6361485+08:00</date></root>'
select #msg.value(N'(xs:dateTime((//root/date/text())[1]))', 'datetime')
The problem is, the datetime format in your XML has more precision in the 'seconds' value than the value() function (and its underlying call to CAST or CONVERT) can handle. See http://msdn.microsoft.com/en-us/library/ms187928(SQL.90).aspx. Conversion type 126 and 127 require .mmm (3 digits of precision), whereas in your original value you have 7.
For debugging steps, consider this:
select #msg.value(N'(//root/date/text())[1]', 'varchar(100)')
> 2009-05-09T13:50:59.6361485+08:00
select #msg.value(N'(xs:dateTime((//root/date/text())[1]))', 'varchar(100)')
> 2009-05-09T05:50:59.636Z