NVARCHAR TO DATETIME conversion - sql

I have a parameter that has a value of 14-Sep-2012 15:47:27 that I would like to update a table column with which is in 2012-08-10 05:00:00.000 format.
What would be the query needed '
#UpdateTime = '14-Sep-2012 15:47:27'
Update tbl
Set Datetimecol = CONVERT(datetime,#UpdateTime,110) ??
I am using SQL Server 2008. Thank you !

For the edited question, you only need to drop the 110 specification. There really isn't a specification for the format you have shown, but English installations of SQL Server will convert it.
e.g.
declare #UpdateTime datetime = '14-Sep-2012 15:47:27'
select CONVERT(datetime,#UpdateTime)
-- result
September, 14 2012 15:47:27
Assuming your month portion is at least 3 characters long, e.g. Mar, Marc, March, Sept, you can convert that very bad text datetime to a normal 3-char month format using the following
declare #updatetime nvarchar(20) = '18-Sept-2012'
declare #fixedtime nvarchar(20)
set #fixedtime = stuff(#updatetime,1,charindex('-',#updatetime),'')
set #fixedtime = Left(#updatetime,charindex('-',#updatetime))
+ stuff(#fixedtime,4,len(#fixedtime)-8,'')
-- #fixedtime contains `18-Sep-2012`
Update tbl
Set Datetimecol = #fixedtime
Yes, I deliberately left out the CAST/CONVERT in the update statement.

As long as your language settings are always English and your regional settings don't change, here is another approach (along with sample data of various potential formats):
DECLARE #x TABLE(y NVARCHAR(15));
INSERT #x VALUES('18-Sept-2012'),('9-May-2012'),('19-Oct-2012'),('04-March-2012');
SELECT z, CONVERT(DATETIME,z) FROM
(
SELECT SUBSTRING(y,s+1,3) + ' ' + LEFT(y,s-1) + ', ' + RIGHT(y,4) FROM
(
SELECT y, CHARINDEX('-',y) FROM #x
) AS y(y,s)
) AS z(z);
Results:
Sep 18, 2012 2012-09-18 00:00:00.000
May 9, 2012 2012-05-09 00:00:00.000
Oct 19, 2012 2012-10-19 00:00:00.000
Mar 04, 2012 2012-03-04 00:00:00.000
You can use the same calculation for a variable:
DECLARE
#y NVARCHAR(15) = N'18-Sept-2012',
#z DATETIME;
SELECT #z = CONVERT(DATETIME,z) FROM
(
SELECT SUBSTRING(y,s+1,3) + ' ' + LEFT(y,s-1) + ', ' + RIGHT(y,4) FROM
(
SELECT #y, CHARINDEX('-',#y)
) AS y(y,s)
) AS z(z);
SELECT #z;
-- UPDATE ...
(Now try with SET LANGUAGE FRENCH; and watch it all go to, well, somewhere.)
For this reason I highly recommend you stop storing / passing dates using the nvarchar type. We have strongly typed date/time types for a reason. When you need to pass a string literal, you should be using unambiguous, standard formats that aren't prone to differences in language, regional and dateformat settings. In this case the right format should be YYYYMMDD:
20120918
For more info, see:
Bad habits to kick : mis-handling date / range queries

Related

How to Convert CYYMM to YYYY-MM

I have some date columns that are formatted as CYYMM (e.g. 12012). I would like to convert these to a typical data representation in SQL Server.
FYI. C stands for century.
E.g. 12012 should be 2020-12 (for December of 2020)
Another
11210 should be 2012-10 (for October of 2012).
How could I go about accomplishing this efficiently and 1900-safe. For example I have accomplished doing it like :
declare #dte int = 12012;
select '20' + left(substring(cast(#dte as char(5)), 2, 5),2) + '-' + right(#dte,2)
But I would like to know if there is a more native solution that doesn't rely on hard coding the '20'.
Assuming first character would be 1 or 0
declare #dte int = 02012;
Select left((#dte/10000+19),2)+stuff(right(#dte,4),3,0,'-')
Results
1920-12

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;

Sql Convert Text Field To Date Field

I'm importing an access database to sql.
The original access database has a date field that imports nicely, but the time field is text (10:00 AM, for instance).
I have over 4000 records and assume there is a way to convert 10:00 AM to 10:00:00.000 (or 07:30 PM to 19:30:00.000, etc...) so that it can be combined with the pre-existing date field (which is now like 2011-11-11 00:00:00.000).
Also, if it's easy to do the conversion and concatenation in the same process, please note.
to convert the time from am or pm 10:00 PM format into time format 10:00:00.000:
select cast(timestring as time(7))
look this:
declare #timeField as varchar(10)
set #timeField = '07:30 PM'
declare #dateField as varchar(10)
set #dateField = '1900-01-01'
select CONVERT(datetime,#dateField + ' ' + CAST(CONVERT(time, #timeField ,121) AS VARCHAR(11)),121)
In your import scripts (I assume you use some sort of SQL to E.T.L your data from Access to SQL server), you can use the convert function as such:
declare #t as time = Convert(time, '10:00PM' )
print #t -- prints 22:00:00.0000000
OR
declare #t as time = Convert(time, '10:00AM' )
print #t -- prints 10:00:00.0000000
And of course if you want to control the precision as per your example:
Convert(time(3), '10:00PM' ) -- prints 22:00:00.000

Convert CMMDDYY into date in SQL Server

If I have a date string in the format of CMMDDYY
C = 0, 1 or 2 where 0 represents 19, 1 represents 20 and 2 represents 21
Example:
1022511 would be 02/25/2011 in mm/dd/yyyy format.
Is there a way to convert this into mm/dd/yyyy format in sql server?
Is CMMDDYY even a valid date format? I haven't found much information on it.
The Year algorithm is simply: (19 + int(C))*100 + int(yy)
Try this:
declare #st nvarchar(7)
set #st = '1030609'
select
cast(
substring(#st,2,2) + '/'
+ substring(#st,4,2) + '/'
+ cast((19 + cast(substring(#st,1,1) as int) )* 100
+ cast(substring(#st,6,2) as int) as nvarchar)
as datetime)
This outputs:
It doesn't sound like a built in date format but you should be able to find it on msdn if it is. If not you could write a function in SQL server that parses a string in that format to a DateTime object

SQL Convert to GMT DateTime

i wan't to convert my records entries from dateTtime+OFFSET to dateTtimeZ directly
(2008-05-11T15:30:00+2--->2008-05-11T13:30:00Z)
with sql functions.
Don't know how to do this :-(
I need to implement this using MySql prefering not using stored procs
Thx
Try this
To convert from GMT to local time:
select DATEADD(hour,DATEDIFF (hour, GETUTCDATE(), GETDATE()),MyGmtDateTime) as LocalDateTime
To convert from local time to GMT:
select DATEADD(hour,DATEDIFF (hour, GETDATE(), GETUTCDATE()),MyLocalDateTime) as GmtDateTime
If I understood your question correctly, there is no way to find out the time zone from time+offset because the mapping is not unique. Several time zones may have the same offset.
Look at this example where multiple time zone have the same offset.
(GMT-06:00) Saskatchewan
(GMT-06:00) Guadalajara, Mexico City, Monterrey - Old
(GMT-06:00) Guadalajara, Mexico City, Monterrey - New
(GMT-06:00) Central Time (US & Canada)
(GMT-06:00) Central America
ADDED: Now I see you asked for something else.
Okay, if the offset in your datetimes is always the same, you can try this transformation.
DECLARE #DateTimeWithOffset datetimeoffset
DECLARE #JustDateTime datetime
SET #DateTimeWithOffset = '2008-05-11 15:30:00 + 02:00'
SELECT #DateTimeWithOffset = SWITCHOFFSET (#DateTimeWithOffset, '00:00')
SELECT #JustDateTime = CAST (#DateTimeWithOffset AS datetime)
This is to give you the idea. I don't have an SQL 2008 right at hand so I haven't tested that. May not work.
I'm pretty rusty with my SQL built-in functions, but in the absence of any standard function, you could write a stored procedure to do the work. Then you could invoke it as part of your SELECT statement:
SELECT to_GMT(invoice_date) from INVOICES
the solution will likely depend of your RDBMS. In Oracle this would work:
SQL> SELECT to_timestamp_tz('2008-05-11T15:30:00+2',
2 'yyyy-mm-dd"T"hh24:mi:ssTZH')
3 AT TIME ZONE 'GMT' gmt_time
4 FROM dual;
GMT_TIME
----------------------------------
11/05/08 13:30:00,000000000 GMT
It is not clear from your question, but I assume you have the values as a string. If so, then extract everything except the offset as a datetime, also get the offset as a datetime, then use the sign to calculate the final result (T-SQL, 2005):
DECLARE #withOffset varchar(30);
SET #withOffset = '2008-05-11T15:30:00+2:00';
PRINT N'Original: ' + CAST(#withOffset AS nvarchar);
DECLARE #dt datetime;
SET #dt = CONVERT(datetime, LEFT(#withOffset, 19), 126);
PRINT N'dt=' + CONVERT(nvarchar, #dt, 127);
DECLARE #ofs datetime;
SET #ofs = CONVERT(datetime, SUBSTRING(#withOffset, 21, LEN(#withOffset) - 21), 108);
PRINT N'ofs=' + CAST(#ofs AS nvarchar);
IF (SUBSTRING(#withOffset, 19, 1) = '+')
BEGIN
SET #dt = DATEADD(hour, DATEPART(hour, #ofs), #dt);
SET #dt = DATEADD(minute, DATEPART(minute, #ofs), #dt);
END
ELSE
BEGIN
SET #dt = DATEADD(hour, -DATEPART(hour, #ofs), #dt);
SET #dt = DATEADD(minute, -DATEPART(minute, #ofs), #dt);
END;
PRINT N'dt=' + CONVERT(nvarchar, #dt, 127);
Use the SQL function CONVERT_TZ(dt,from_tz,to_tz).
CONVERT_TZ() converts a datetime value dt from the time zone given by
from_tz to the time zone given by to_tz and returns the resulting
value.
Example:
UPDATE this_table
SET this_table_date_gmt = (
SELECT CONVERT_TZ(this_date, '+00:00', '-02:00')
)
Reference : https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_convert-tz