Convert a string ddmmyyyyhhmi into yyyy-mm-dd in SQL server - sql

how can I convert a string ddmmyyyyhhmi into yyyy-mm-dd?
A string 210420161701 (a varchar) into 2016-04-21 (a datetime data type).
I tried a combination of sub-string, cast, convert but can't seem to make it work.
Please kindly help thanks.

The first 2 lines are just setting up the variable, but the following works (as long as the format is always the same). You may also need to make sure the date format of your SQL installation is correct (SET DATEFORMAT). You can also change the datatype from date to datetime if required.
DECLARE #Date Varchar(100) = '210420161701'
DECLARE #DateVariable date
SELECT #DateVariable = SUBSTRING(#date,5,4) + '-' + SUBSTRING(#date,3,2) + '-' + SUBSTRING(#date,1,2)
SELECT #DateVariable

select
SUBSTRING(convert(varchar(10),'210420161701',103),5,4)+ '-'+
SUBSTRING(convert(varchar(10),'210420161701',103),3,2)+'-'+
SUBSTRING(convert(varchar(10),'210420161701',103),1,2)

Related

Change the numeric format into 'AM/PM' format in CONCAT / MAX (sql)

I need to change the numeric format into 'AM/PM' format in CONCAT function (I use SSMS v 18.5.1)
Here is my formula. RCLDTE - is a date and RCLTIM is time. I basically need to leave RCLDTE as it is and change the format of RCLTIM from numeric to date and convert to AM/PM format.
How the column looks right now
Format of RCLTIM - numeric
CONCAT(c.RCLDTE, ' & ', MAX(c.RCLTIM)) AS 'Date & Time',
When I tried to use CONVERT function as I tend to use, it raised an error.
CONCAT(c.RCLDTE, ' & ', CONVERT(varchar(15),CAST( MAX(c.RCLTIM) AS TIME),100))
Error
Explicit conversion from data type numeric to time is not allowed.
The number for the date can be concatenated to the number for the time stuffed with colons. So that it can be converted to a DATETIME.
And by using FORMAT the DATETIME can be put in a specific format.
(But use CONVERT if it has the format.)
Test snippet
declare #test table (
ID INT IDENTITY PRIMARY KEY,
RCLDTE int,
RCLTIM int
);
insert into #test (RCLDTE, RCLTIM) values
(20220119, 215250)
, (20220304, 070809)
;
select
FORMAT(TRY_CAST(CONCAT(c.RCLDTE, ' ', STUFF(STUFF(FORMAT(MAX(c.RCLTIM),'000000'),5,0,':'),3,0,':')) AS DATETIME)
, 'd/M/yyyy hh:mm:ss tt') AS [Date & Time]
from #test c
group by RCLDTE;
Date & Time
19/1/2022 09:52:50 PM
4/3/2022 07:08:09 AM
Test on db<>fiddle here
What you're attempting to do is very fragile, but I presume your source system gives you few options.
Converting like this has potential problems with DST & the language in use at the time of running.
Your question lost some of the detail regarding formats, so I can't see the time type you are using, but it looks like a decimal again.
Essentially, you need to put the the numerics in a string and then into datetime columns, but to get there you have to match a string conversion format the sqlserver.
Fortunately you are not far off the us format default.
Something like this will get you a date field, you can then amend the output format if you really need 12hr rather than 24hr.
SET LANGUAGE us_english
DECLARE #rcldte NUMERIC, #rcltim numeric
SET #rcldte=20220119
SET #rcltim = 015250
SELECT
CONVERT(DATETIME, CAST (#rcldte AS VARCHAR)+ ' ' +
LEFT( left('000000', 6-LEN(CAST ( #rcltim AS VARCHAR)))+CAST ( #rcltim AS VARCHAR),2)
+ ':' + substring( left('000000', 6-LEN(CAST ( #rcltim AS VARCHAR)))+CAST ( #rcltim AS VARCHAR),3,2)
+ ':' + RIGHT( left('000000', 6-LEN(CAST ( #rcltim AS VARCHAR)))+CAST ( #rcltim AS VARCHAR),2))
Which will give you:
(No column name)
2022-01-19 01:52:50.000
It's rather ugly though.
If you can guarantee the hours are zero padded then you could remove the complexity associated with that.
And if you're really going to use it then split into proper UDFs...
DECLARE #RCLDTE CHAR(8) = '20220119';
DECLARE #RCLTIM CHAR(6) = '215250';
select CONVERT(VARCHAR(21), (cast(#RCLDTE as DATETIME) + cast(substring(#RCLTIM,1,2)+':'+substring(#RCLTIM,3,2)+':'+substring(#RCLTIM,5,2) as DATEtime) ), 22);
output: 01/19/22 9:52:60 PM
For different formats of the DATETIME, see the docs of the CONVERT function:
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15
NOTE: When specifying another format the value 21 in VARCHAR(21) might need a change...

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;

update date format in SQL developer

I need to convert date format in SQL
The current format is yyyy/mm/dd-hh:mm:ss:sss and I need to convert it to yyyy-mm-dd hh:mm:ss CST
I don't really know SQL but did some research and found that I can use instr to find the string and replace it, however, no matter what I try,there is always something off :(
Could anyone here help me with it? thanks in advance.
By the way, it's in oracle sql developer so syntax are different from previous answer. Thanks again
If your current column is stored as a varchar (which it looks like it is based on your example) you can convert it the following way to a datetime.
declare #date varchar(25)
set #date = '2012/02/16-09:40:30:000'
select Convert(datetime, Left(#date, 4) + '-' +
substring(#date, 6, 2) + '-' +
substring(#date, 9, 2) + ' ' +
substring(#date, 12, 8)) As NewDate
And the result would be 2012-02-16 09:40:30.000
There are lots of sites that have details on converting datetime:
http://www.sql-server-helper.com/tips/date-formats.aspx
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/
If the date is stored as a datetime, then you can get your format by doing:
SELECT convert(varchar, getdate(), 120)
thank you so much for your guys help! I got this sorted out by other user's help, the command is,
update b
set first= to_char(substr(FIRST,1,4)||'-'||substr(FIRST, 6, 2)||'-'||substr(FIRST, 9, 2)||' '||substr(FIRST, 12, 8))
Thanks :)
Mylie
The CONVERT() function is normally used for this. The third parameter lets you specify the required date formatting.
If the date is already in a string, then convert it first into a date type and then convert it back to a string in the required format.
http://msdn.microsoft.com/en-us/library/ms187928.aspx
If you're using SQL Server and it's a date field you can do:
convert(varchar,getdate(),120)
Replacing getdate() with the column name
If the date is stored as a DATETIME, then you can convert it to a string in the format you want by doing the following:
SELECT CONVERT(VARCHAR(19),YourColumn,120)
FROM YourTable
CAST AND CONVERT
declare #ds varchar(23)='2012/02/16 12:57:03:002'; --your current format
select convert(varchar(30),cast(#ds as datetime),120)+' CST' --new format you specified

T-SQL convert varchar yyyy-MM-dd-hh.mm.ss.nnnnnn into datetime

This is in MS SQL Server.
I have a varchar in the format yyyy-MM-dd-hh.mm.ss.nnnnnn
For example: 2010-09-17-20.52.31.870000
I want to convert this into a datetime... but ISDATE function in MSSQL says that is not a valid date and CONVERT won't work. Is there a way to use the convert function so that I can tell it what format the date is in?
I also want to check first that it is a valid date since the varchar input may contain nothing or it may contain an invalid date.
For example, invalid data of 2010-xx-r7-99.53esdfd.31.870000... I would skip that data and not even try to convert.
As far as I'm aware, SQL Server 2005 only supports milliseconds up to 3 digits, so you could replace the periods with colons, and grab the left and right portions (ignoring the hyphen between the day and hours) and come up with something like this:
DECLARE #myDate varchar(50)
SET #myDate = '2010-09-17-20.52.31.870000'
PRINT isdate(left(#myDate, 10) + ' ' +
replace(substring(#myDate, 12, 12), '.', ':')) -- Should print '1'
PRINT cast(left(#myDate, 10) + ' ' +
replace(substring(#myDate, 12, 12), '.', ':') as datetime)
... which will effectively give you 870 milliseconds
The ISO 8601 standard separates the date and time with the letter T. Maybe that's all it needs to convert successfully? Some conversion implementations accept a space there too. I've never seen a hyphen there.
You would have to change the punctuation a bit to make it work, and reduce the precision from microseconds to millisecond. This works:
convert(datetime, '2010-09-17 20:52:31.870', 121)
What you are getting in is a bit wonky, but this works (tested):
DECLARE #temp as varchar(50)
SET #temp = '2010-09-17-20.52.31.870'
SET #temp = replace(#temp,'.',':')
set #temp = stuff(#temp,11,1,'T')
set #temp = stuff(#temp,20,1,'.')
select #temp
select cast(#temp as datetime)
NB I cut off the extra 0s, you could do this with substring if there really are those extra ones.

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.