convert varchar(ddmmyyyy) to date format - sql

How can I convert, for example, ddmmyyyy which is a varchar(8) to date format(dd/mm/yyyy)?
I have a stored procedure which accepts a date varchar(8) parameter.
I want to convert it to date format before inserting into database.
I tried to use
INSERT INTO mytable(createdDate) VALUES (CONVERT(date, CONVERT(varchar(8), #date), 106));
An error:
Conversion failed when converting date and/or time from character string.
createdDate column is type : date

ddmmyyyy is not a valid date format. You need to first make that string into something that can be parsed as a DATE / DATETIME. The quickest way might be to simply SUBSTRING the pieces into a mm/dd/yyyy format. That does convert successfully. But you have a VARCHAR(8). So you either need to increase that to be VARCHAR(10) (or better yet, just CHAR(10)), or declare a local variable to hold the altered value.
For example:
DECLARE #Date VARCHAR(8); -- input parameter
SET #Date = '25032014';
DECLARE #Date2 CHAR(10);
SET #Date2 = SUBSTRING(#Date, 3, 2)
+ '/' + SUBSTRING(#Date, 1, 2)
+ '/' + SUBSTRING(#Date, 5, 4);
SELECT #Date2, CONVERT(DATE, #Date2);
-- 03/25/2014 2014-03-25
EDIT:
Actually, I found a slightly simpler way. I started out with this method but realized that it did not work with ddmmyyyy as opposed to mmddyyyy. I somehow missed that there was an appropriate date style number for dd/mm/yyyy. So, simply adding two slashes to the incoming string and then calling CONVERT does work, but only if you use 103 as the "style". And like the first solution, it requires either changing the incoming parameter to be VARCHAR(10) or CHAR(10) instead of VARCHAR(8), or creating a local variable to be CHAR(10).
DECLARE #Date VARCHAR(8); -- input parameter
SET #Date = '25032014';
DECLARE #Date2 CHAR(10);
SET #Date2 = STUFF(STUFF(#Date, 3, 0, '/'), 6, 0, '/');
SELECT #Date2, CONVERT(DATE, #Date2, 103); -- 103 = dd/mm/yyyy
-- 25/03/2014 2014-03-25
Conversion "styles" can be found on the MSDN page for CAST and CONVERT.

Related

String to Date in SQL

Is there a way to quickly convert this date format to DATE in SQL?
{ “date_from”:”22112017”,”date_to”:”22112017”}
This is needed to filter the data between these dates
(There are a lot of conversion entries on the web, but I haven't found that format)
EDIT:
DECLARE #EndDate DATE = CONVERT(VARCHAR, '22112017', 103)
PRINT #EndDate
Error: Conversion failed when converting date and/or time from character string.
WHAT I HAVE:
#StartDate = '22112017'
#EndDate = '22112020'
WHAT I NEED TO DO:
SELECT * from tblMy WHERE ReceivedDate BETWEEN #StartDate AND #EndDate
If you fix your JSON to not use stylised double quotes (”) and use standard ones (") then you can parse this as JSON. Once you extract the values, you can inject a couple of / characters in and then convert to a date with the style code 103 (dd/MM/yyyy):
DECLARE #String nvarchar(MAX) = N'{ "date_from":"22112017","date_to":"22112017"}';
SELECT CONVERT(date,STUFF(STUFF(OJ.date_from,5,0,'/'),3,0,'/'),103) AS date_from,
CONVERT(date,STUFF(STUFF(OJ.date_to,5,0,'/'),3,0,'/'),103) AS date_to
FROM (VALUES(#String))V(S)
CROSS APPLY OPENJSON(V.S)
WITH (date_from varchar(8),
date_to varchar(8)) OJ;
Edit:
Seems the OP has moved their goal posts, this has nothing to do with JSON.
The problem here is your literal strings. When using literal strings for a date and time data type use either yyyyMMdd or yyyy-MM-ddThh:mm:ss.nnnnnnn as they are both unambiguous regardless of language and data type:
DECLARE #StartDate date,
#EndDate date;
SET #StartDate = '20171222';
SET #EndDAte = '20201122';
SELECT *
FROM tblMy
WHERE ReceivedDate BETWEEN #StartDate AND #EndDate;
I would suggest converting the value to a standard SQL Server date value. This is pretty simple:
select convert(date, left(val, 4) + substring(val, 3, 2) + right(val, 2))
The standard date format is YYYYMMDD. Yours is DDMMYYYY, so string operations can convert it to the correct format. Of course, what you should probably do is to convert the value to a date in the application layer and pass the date value in as a parameter.
This should fix the error "Error: Conversion failed when converting date and/or time from character string."
DECLARE #EndDate VARCHAR(MAX) = '22112017'
DECLARE #datevar date = CAST(SUBSTRING(#EndDate, 3, 2) + '/' + SUBSTRING(#EndDate,
1, 2) + '/' + SUBSTRING(#EndDate, 5, 4) AS date);
SELECT #datevar;

Error converting data type varchar to date converting an int year into a string

I have SchoolYear variable as an INT, and I'm trying to set a variable to this:
SET #BeginDate = '07/01/' + CONVERT(VARCHAR(4), #SchoolYear - 1)
It gives me the 'Error converting data type varchar to date' error.
Example:
#SchoolYear INT = 2019,
#BeginDate Date - NULL
Desired result:
07/01/2018
What am I doing wrong please?
Check out DATEFROMPARTS (available from SQL 2012), and bypass strings altogether.
SET #BeginDate = DATEFROMPARTS(#SchoolYear - 1, 1, 7)
1st arg = year, 2nd = month, 3rd = day.
The format you are using is simply not understood by your sql server.
When dealing with dates in varchar columns/variables it is best to use a date format that is language neutral.
yyyyMMdd is such a format, it will always work no matter what regional settings are used on your server.
See also this http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes
in your case you should use
SET #BeginDate = CONVERT(VARCHAR(4), #SchoolYear - 1) + '0107'
that is assuming that 01 is the month, and 07 is the day so you end up with 20180107
Better would be off course to avoid varchar complete when converting, like this
set #BeginDate = DATEFROMPARTS(#SchoolYear - 1, 1, 7)
Maybe you should use the yyyy-mm-dd format and change the set as:
SET #BeginDate = CONVERT(VARCHAR(4), #SchoolYear - 1)+ '-01-07'
Declare #SchoolYear int
Set #SchoolYear = 2019
Declare #BeginDate varchar(50)
SET #BeginDate = '07/01/' + CONVERT(VARCHAR(4), #SchoolYear - 1)
--Once You have you varchar populated, you can use Convert Function to convert
--to datetime and select the format you want
Select CONVERT (Datetime,#BeginDate, 101)

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;

Conversion failed converting datetime from string

I am trying to convert my three parameters to a DATETIME but its not working. I get the error that the conversion failed when converting datetime from character string whenever I run this query. Perhaps I am doing in wrong in the conversion? If anyone can provide any feedback.
#month varchar,
#day varchar,
#year varchar
AS
DECLARE #date DATETIME
SET #date = Convert(DateTime, #month + '/' + #day + '/' + #year, 101)
Select *
From events
Where (EDate = #date) OR EDateEnd = #date OR #date Between EDate AND EDateEnd
Order By EDate ASC
You need to set the size of your parameters. Probably something like
#month varchar(2),
#day varchar(2),
#year varchar(4)
That should be working. Make sure you have provided valid values in you parameters.
Update
You should lose the 101 parameter for conversion. Provided that parameters are informed with valid values, this should work for both 2-digit and 4-digit years:
SET #date = Convert(DateTime, #month + '/' + #day + '/' + #year)
This is just a guess, because the conversion function shown should work with the proper parameters.
Are you passing in the year as a two-digit number? If so, try passing it as the full four digit year (which the "101" format expects) OR change it to
SET #date = Convert(DateTime, #month + '/' + #day + '/' + #year, 1)
if you're passing in a 2 digit year.
(See the difference for with century and without century here: http://msdn.microsoft.com/en-us/library/ms187928.aspx)
EDIT
I have a second guess... The error may not be on the line where you're explicitly converting the parameters into a Datetime variable. This has burned me before... The error MAY be occurring on the following line:
Where (EDate = #date) OR EDateEnd = (#date) OR #date Between EDate AND EDateEnd
if the EDate column or EDateEnd column is not necessaryly a DateTime column. It could be that THOSE contain the values that can't be converted to a DateTime. (They could be char fields, with a DateTime string stored in them, or they could be actual Date fields with null values stored in them.)
However, without more information about the actual schema of the database it's hard to tell. The best we can do is guess.

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.