Query: Assigning error datetime2 - sql

I want to assign '1392-04-31' using this code:
DECLARE #t DATETIME
SET #t = '92-04-31'
I see this error:
Conversion failed when converting date and/or time from character string.
Any one know why?

The solution is:
use datetime2!
DECLARE #t datetime2
SET #t = '1392-04-30'
Because you can't use datetime:
The minimum date stored in datetime is January 1, 1753. So 1392 is not storeable.
April has 30 days.
Using formatted date with datetime:
Second, when you write a date in Sql Server, the format I prefer is {d 'YYYY-MM-DD'}, so in your case becomes:
DECLARE #t DATETIME
SET #t = {d '1992-04-30'}
To complete this discussion, if you want use hh mm ss so you must use this format: {ts 'yyy-mm-dd hh:mm:ss.mmm'}
DECLARE #t DATETIME
SET #t = {ts '1992-04-30 23:59:59.123'}

try this :
declare #t DATETIME
set #t = '1992-04-30 10:54:30'

The date you are trying to set is probably invalid.
Also there are several ways of representing dates in SQL as a string, depending on Language, Dateformat and other setting. Typically the safest way to do this is to use the 'YYYYMMDD' format.
The article below will also answer the question : Why is 1753 the earliest date for datetime?
You should read this if you would like some detailed information:
http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes

First of all, April only has 30 days. I'm not going to take the time to look up historically whether that was the case in 1392, but either way I'm pretty sure the date 4/31/1392 is invalid for a SQL Server DATETIME.
Also, you should use the full year in the format '01-01-2013'.
Try the following and you'll get the output Jan 1 2013 12:00AM.
declare #t DATETIME
set #t = '01-01-2013'
PRINT #t
The above should work for any valid date.

Related

SQL Server date conversion is 68 years behind the actual date

I want to convert an integer to a date format. I am using the following script:
SELECT CAST(7549 as datetime)
It returns me a date 1920-09-02
However, 7549 actual date is 1988-08-31
Can anyone please help me how to perform correct mapping?
See the reverse
DECLARE #YourDate AS Datetime
SET #YourDate = '1920-09-02'
SELECT CAST(#YourDate AS INT) --7549
SET #YourDate = '1988-08-31'
SELECT CAST(#YourDate AS INT) -- 32384
If you want the result as '1988-08-31 00:00:00.000', try with the following scripts.
SELECT CAST(7549 as datetime)-CAST('1832-01-03' as datetime)
OR
SELECT CAST(7549 as datetime)+CAST(24835 as datetime)

Convert from nvarchar to DateTime with am pm?

In my table I have myDate column of type nvarchar(50).
The result I need is to select this date/time: 07/11/2013 11:22:07
And I need to get 07/11/2013 11:22:07 am from it (add am/pm to the original date&time).
I tried everything but get only the original data without am/pm.
This is an example from my query :
select convert(dateTime,myDate,100) as Date from Info
or
select convert(dateTime,myDate,0) as Date from Info
What am I missing ?
try this !!
declare #date datetime
set #date='07/11/2013 11:22:07'
SELECT cast(convert(varchar(20),substring(convert(nvarchar(20),#date, 9), 0, 21)
+ ' ' + substring(convert(nvarchar(30), #date, 9), 25, 2),105) as datetime)
Your field is a NVARCHAR field so just return it without any conversion. In your query you convert string representation into the DATETIME type and returns it. Your browser software which shows query results convert DateTime value into string representation to show it to you and conversion format depends on this software usually you can change it changing Windows Regional Settings.
You can get AM/PM data using following query
declare #date datetime
select #date= CAST('07/11/2013 11:22:07' AS datetime)
select RIGHT ( CONVERT(VARCHAR,#date,9),2)

Char to DateTime Conversion

I have one column capturedatetime(Char(30)):
2006-04-25T15:50:59.997000 PM
And I want to convert it and load it at other table column which have is in DateTime. either by T-sql or SSIS which ever way.
I have tried with:
select CONVERT(datetime, '2006-04-25T15:50:59.997000 PM', 126)
But it creates an error:
Conversion failed when converting date and/or time from character string
Late update:
In this column I also have other data that is in a completely different format:
29-JAN-10 08.57.41.000000 PM
(1) STOP storing datetime data in string columns! This is nothing, nothing, nothing but trouble.
(2) Why on earth does your column get data in two different string formats that aren't even valid? Why does the string use 24 hour time and have AM/PM suffix? Why use a regional string format and Y2K disaster like 29-JAN-10?
Here is one way, but it's awfully ugly. I highly recommend you fix the SSIS process to give you valid datetime values in the first place, if not as datetimes, at least as valid ISO strings (yyyy-mm-ddThh:mm:ss.nnn):
DECLARE #x TABLE (d CHAR(30));
INSERT #x SELECT '2006-04-25T15:50:59.997000 PM'
UNION ALL SELECT '29-JAN-10 08.57.41.000000 PM';
SET LANGUAGE ENGLISH; -- this is important, else style 6 may not work
SELECT
CASE WHEN d LIKE '__[0-9]%' THEN
CONVERT(DATETIME, LEFT(d, 23))
WHEN d LIKE '[0-9][0-9]-%' THEN
CONVERT(DATETIME, CONVERT(CHAR(8),
CONVERT(DATETIME,REPLACE(LEFT(d,9),' ','-'),6),112)
+ ' ' + REPLACE(SUBSTRING(d,11,8),'.',':')
+ ' ' + RIGHT(RTRIM(d),2))
END
FROM #x;
The conversion for 126 requires no spaces ... I've got it to work like this:
declare #T varchar(50)
declare #dt datetime
set #T = '2006-04-25T15:50:59.997'
set #dt = convert(datetime,#t,126)
select #T, #dt
select convert(datetime,left('2006-04-25T15:50:59.997000 PM',23))
or
select convert(datetime,left(capturedatetime,23))
If you use cast, you do not even need to supply a format. Code snippet below tested on SQL 2012 Developer version.
declare #var_string varchar(50) = '2006-04-25T15:50:59.997';
declare #var_datetime datetime = cast(#var_string as datetime);
select #var_string as my_string, #var_datetime as my_variable;

T-SQL 2008 Convert Date and time string to datetime

I have two columns in my table, one to capture time and one to capture date. Unfortunately, both are varchar(). I need to take the two fields, concatenate them together, and then convert them to datetime.
I am trying to accomplish that with this:
select CONVERT(datetime,(select txt_returned_date+' '+CONVERT(varchar(20),CONVERT(TIME,txt_time_returned))),126)
from table_name
I am getting this error message:
Conversion failed when converting date and/or time from character string.
The date is being captured as "20130308" as a string. Time is being captures as "4:27 PM" as a string
What I am doing here is converting the string of the time to TIME, then back to varchar. Then I am concatenating them together. This works by itself, but once I introduce the CONVERT(datetime) to the whole query, it is giving me the error.
Any help to try to accomplish this is helpful. Thanks!
You can concatenate the DATE and TIME values together once they have been converted to a DATETIME. Here's a sample to play with that shows concatenating a DATE column and a TIME column that have been stored as VARCHAR:
-- Set up some variables to test with
DECLARE #myTime TIME = GETDATE()
, #myDate DATE = GETDATE()
, #myTimeTxt VARCHAR(16)
, #myDateTxt VARCHAR(10);
-- Initialize your variables
SELECT #myTimeTxt = #myTime
, #myDateTxt = #myDate;
-- Display your separated values
SELECT #myDateTxt, #myTimeTxt;
-- Display your concatenated value
SELECT CAST(#myDateTxt AS DATETIME) + CAST(CAST(#myTimeTxt AS TIME) AS DATETIME);
You can use this option
DECLARE #date date = '20010101',
#time time = '01:01:01'
SELECT CAST(#date AS datetime) + #time
Result:2001-01-01 01:01:01.000
Demo on SQLFiddle
Are you using SQL 2012? If so you may be able to use the datetimedromparts function to achieve this. If not for this specific example, it's always good to know for the future :)
http://technet.microsoft.com/en-gb/library/hh213233.aspx

Convert varchar into datetime in SQL Server

How do I convert a string of format mmddyyyy into datetime in SQL Server 2008?
My target column is in DateTime
I have tried with Convert and most of the Date style values however I get an error message:
'The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.'
OP wants mmddyy and a plain convert will not work for that:
select convert(datetime,'12312009')
Msg 242, Level 16, State 3, Line 1
The conversion of a char data type to a datetime data type resulted in
an out-of-range datetime value
so try this:
DECLARE #Date char(8)
set #Date='12312009'
SELECT CONVERT(datetime,RIGHT(#Date,4)+LEFT(#Date,2)+SUBSTRING(#Date,3,2))
OUTPUT:
-----------------------
2009-12-31 00:00:00.000
(1 row(s) affected)
SQL Server can implicitly cast strings in the form of 'YYYYMMDD' to a datetime - all other strings must be explicitly cast. here are two quick code blocks which will do the conversion from the form you are talking about:
version 1 uses unit variables:
BEGIN
DECLARE #input VARCHAR(8), #mon CHAR(2),
#day char(2), #year char(4), #output DATETIME
SET #input = '10022009' --today's date
SELECT #mon = LEFT(#input, 2), #day = SUBSTRING(#input, 3,2), #year = RIGHT(#input,4)
SELECT #output = #year+#mon+#day
SELECT #output
END
version 2 does not use unit variables:
BEGIN
DECLARE #input CHAR(8), #output DATETIME
SET #input = '10022009' --today's date
SELECT #output = RIGHT(#input,4) + SUBSTRING(#input, 3,2) + LEFT(#input, 2)
SELECT #output
END
Both cases rely on sql server's ability to do that implicit conversion.
Likely you have bad data that cannot convert. Dates should never be stored in varchar becasue it will allow dates such as ASAP or 02/30/2009. Use the isdate() function on your data to find the records which can't convert.
OK I tested with known good data and still got the message. You need to convert to a different format becasue it does not know if 12302009 is mmddyyyy or ddmmyyyy. The format of yyyymmdd is not ambiguous and SQL Server will convert it correctly
I got this to work:
cast( right(#date,4) + left(#date,4) as datetime)
You will still get an error message though if you have any that are in a non-standard format like '112009' or some text value or a true out of range date.
I found this helpful for my conversion, without string manipulation. https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
CONVERT(VARCHAR(23), #lastUploadEndDate, 121)
yyyy-mm-dd hh:mi:ss.mmm(24h) was the format I needed.
Convert would be the normal answer, but the format is not a recognised format for the converter, mm/dd/yyyy could be converted using convert(datetime,yourdatestring,101) but you do not have that format so it fails.
The problem is the format being non-standard, you will have to manipulate it to a standard the convert can understand from those available.
Hacked together, if you can guarentee the format
declare #date char(8)
set #date = '12312009'
select convert(datetime, substring(#date,5,4) + substring(#date,1,2) + substring(#date,3,2),112)
Look at CAST / CONVERT in BOL that should be a start.
If your target column is datetime you don't need to convert it, SQL will do it for you.
Otherwise
CONVERT(datetime, '20090101')
Should do it.
This is a link that should help as well:
I'd use STUFF to insert dividing chars and then use CONVERT with the appropriate style. Something like this:
DECLARE #dt VARCHAR(100)='111290';
SELECT CONVERT(DATETIME,STUFF(STUFF(#dt,3,0,'/'),6,0,'/'),3)
First you use two times STUFF to get 11/12/90 instead of 111290, than you use the 3 to convert this to datetime (or any other fitting format: use . for german, - for british...) More details on CAST and CONVERT
Best was, to store date and time values properly.
This should be either "universal unseparated format" yyyyMMdd
or (especially within XML) it should be ISO8601: yyyy-MM-dd or yyyy-MM-ddThh:mm:ss More details on ISO8601
Any culture specific format will lead into troubles sooner or later...
use Try_Convert:Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.
DECLARE #DateString VARCHAR(10) ='20160805'
SELECT TRY_CONVERT(DATETIME,#DateString)
SET #DateString ='Invalid Date'
SELECT TRY_CONVERT(DATETIME,#DateString)
Link:MSDN TRY_CONVERT (Transact-SQL)
I had luck with something similar:
Convert(DATETIME, CONVERT(VARCHAR(2), #Month) + '/' + CONVERT(VARCHAR(2), #Day)
+ '/' + CONVERT(VARCHAR(4), #Year))
The root cause of this issue can be in the regional settings - DB waiting for YYYY-MM-DD while an app sents, for example, DD-MM-YYYY (Russian locale format) as it was in my case. All I did - change locale format from Russian to English (United States) and voilĂ .
This seems the easiest way..
SELECT REPLACE(CONVERT(CHAR(10), GETDATE(), 110),'-','')
SQL standard dates while inserting or updating Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
So if you are inserting/Updating below 1/1/1753 you will get this error.
DECLARE #d char(8)
SET #d = '06082020' /* MMDDYYYY means June 8. 2020 */
SELECT CAST(FORMAT (CAST (#d AS INT), '##/##/####') as DATETIME)
Result returned is the original date string in #d as a DateTime.