Convert data and time into a numeric number in sql server - sql

I have a data & time format column which I would like to convert to the following format in Microsoft SQL Server: yyyymmddhhmmss00000
So for example if I have 2021-02-04 11:49:50 this will be converted to 2021020411495000000.
Any one knows how to do it please?

You can use the FORMAT function:
SELECT FORMAT(myDate, 'yyyyMMddHHmmss00000')

By converting the date to NVARCHAR once with format 112 and once with format 8 you can extract the numeric date and the time without milliseconds. After removing : from the time you can concat these two strings and convert them to bigint. Following an example:
DECLARE #d DATETIME = GETDATE()
SELECT CAST(CONVERT(NVARCHAR(8), #d, 112) + REPLACE(CONVERT(NVARCHAR(8), #d, 8), ':', '') + '00000' AS BIGINT)

Related

How to convert from string stored yyyymmdd format to date

I have a date that is stored as a string and I want to convert or cast it from varchar to date. It is stored as yyyymmdd in string. The date output should be in yyyymmdd format, date data type:
DECLARE #UntilRule nvarchar(50)
DECLARE #UntilDate date
SET #UntilRule = 20200601
SET #UntilDate = FORMAT(CAST(SUBSTRING(#UntilRule, CHARINDEX('=', #UntilRule) + 1, 8) AS date), 'yyyymmdd')
I get the following error:
Conversion failed when converting date and/or time from character string.
You can just do:
select convert(date, #UntilRule)
Your format is the SQL Server standard for dates.

Using Substring and Convert Datetime Sql Server 2017

This is my query:
declare #date char(10)
set #date = '11.08.1982'
select substring(#date,1,2)+ '/'+
SUBSTRING(#date,3,1)+ '/'+ SUBSTRING(#date,4,4) as resultat
I want to use CONVERT function to convert the result to datetime. How can I do this?
You can't convert this to date and time, however you can use replace function :
select replace(#data, '.', '/')
SQL Server is pretty good about picking up the format of a date with no conversion format. So, this works on db<>fiddle, assuming you intend MM.DD.YYYY for the format:
select convert(date, '11.08.1982')
If you want DD.MM.YYYY, then you can explicitly use the "104" format:
select convert(date, '11.08.1982', 104)
You don't have a time component, so I converted these to date. The same works for datetime.

Convert to Datefrom dd/mm/yyyy string SQL

I currently have a string in the format dd/mm/yyyy which I'm trying to convert to a datetime variable in SQL.
I'm currently using this SQL statement:
CONVERT(datetime, ProposedTransferDate.AttributeValue, 101)
but I get an error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Thanks
Chris
You should be using mask 103:
CONVERT(datetime,ProposedTransferDate.AttributeValue, 103)
From this TechOnTheNet article we find that mask 103 has the following format:
dd/mm/yy (British/French standard)
Use string manipulation to get it into a yyyy-mm-dd format:
CAST(
RIGHT(ProposedTransferDate.AttributeValue,4) +
'-' +
RIGHT(LEFT(ProposedTransferDate.AttributeValue,5),2) +
'-' +
LEFT(ProposedTransferDate.AttributeValue,2)
AS DATETIME)
That conversion error is due to your date column is not standard and unique SQL/ISO date formatwhich is YYYY-MM-DD. your date format may be in MM/DD/YYYY so if your login default Language UK means Date format will be like DD/MM/YYYY.So before convert you want change the default language in SQL SERVER .This link to show types of languages and learn about SET LANGUAGE(TSQL)
EG
SET LANGUAGE 'british english'
select convert(date,GETDATE(),103) ------------use date then it show only date
you can use another way also
SET LANGUAGE 'british english'
select DATEPART(dd,'2-3-2012')+ '/' + DATEPART(mm,'2-3-2012')+ '/' + DATEPART(yy,'2-3-2012')
or
SET LANGUAGE 'british english'
select CONCAT(DATEPART(dd,'2-3-2012'), '/' , DATEPART(mm,'2-3-2012'), '/' ,DATEPART(yy,'2-3-2012'))
Try this:
SELECT convert(datetime, '23/10/2016', 103)
Result:
2016-10-23 00:00:00.000

Convert varchar to datetime in sql which is having millisec

I have a column abc varchar(100) with data like 2011-09-26 16:36:57.810000
I want to convert this column to DATETIME...
But doing a
Convert(DATETIME, abc,120)
is giving this error:
Conversion failed when converting date and/or time from character string.
Can any one please help me convert my varchar format to datetime in SQL Server 2008?
Thanks in advance
You can use style 121 but you can have only 3 digits for milliseconds (i.e yyyy-mm-dd hh:mi:ss.mmm(24h)) format.
declare #abc varchar(100)='2011-09-26 16:36:57.810'
select convert(datetime,#abc,121)
So you can sort it out by limiting the varchar field to 23 characters before converting as:
declare #abc varchar(100)='2011-09-26 16:36:57.810000'
select convert(datetime,convert(varchar(23),#abc),121)
Or use the Left() function to get first 23 characters as:
select convert(datetime,left(#abc,23),121)
Try to avoid storing date as string.
In case you need 6 digits precision use DATETIME2
SELECT CONVERT(DATETIME2, '2016-08-09T08:08:50.358000', 126) as MSSQLDateTime2
SELECT CONVERT(DATETIME, '2016-08-09T08:08:50.358', 126) as MSSQLDateTime
SQL Server only supports 3 decimal places for milliseconds, so the following will work:
Convert(DATETIME, SUBSTRING(abc, 0, 24) ,120)
Based on GBrian's answer, I came up with:
CONVERT(DATETIME, CONVERT(DATETIME2, abc, 126))
I haven't benchmarked how this stacks up against the substring-based solutions.
Assuming we have the following string variables:
DECLARE #d VARCHAR(100) = '2020-04-06T04:35:07.9490051Z' -- 7 digits nanoseconds
DECLARE #d1 VARCHAR(100) = '2020-04-05T15:00:00Z' -- simple: without nanoseconds
I came up to the solution using CAST operator:
SELECT CAST(LEFT(#d,19) + 'Z' AS DATETIME) -- outputs: 2020-04-06 04:35:07.000
SELECT CAST(LEFT(#d1,19) + 'Z' AS DATETIME) -- outputs: 2020-04-05 15:00:00.000

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.