Conversion failed converting datetime from string - sql

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.

Related

SQL Convert data time format (yyyy-mm-dd 00:00:00.000) to yyyymmdd as int

It must be very simple, but I don't know SQL language very well.
I need to filter data by date which is in this format:
How to do it right to filter data this way?
FROM [TableName] where
FileDate>=20220505
I've already tried the command LEFT and CAST but with no success
Something like this may work:
declare #now Datetime = getdate();
declare #intNow int = cast(cast(datepart(year, #now) as varchar(4)) + RIGHT('00'+CAST(datepart(month, #now) AS VARCHAR(2)),2) + RIGHT('00'+CAST(datepart(day, #now) AS VARCHAR(2)),2) as int)
Although if you have your date to check against in the right format e.g. using:
declare #dateToCheck Datetime = cast(cast(20220505 as varchar) as datetime)
And then
FileDate>= #dateToCheck
it should work
You can create an integer representation of your datetime by multiplying and adding the date parts:
year * 10000 20220000
month * 100 500
day 5
-------------------------
20220505
...
FROM [TableName]
WHERE (DATEPART(year, [FileDate]) * 10000) + (DATEPART(month, [FileDate]) * 100) + (DATEPART(day, [FileDate])) >= 20220505
However I'd still look into fixing the condition input format instead.
Credit to #Rangani in Yesterday's date in SSIS package setting in variable through expression for "multiply and add instead of string concat" trick

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)

convert varchar(ddmmyyyy) to date format

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.

Transforming nvarchar day duration setting into datetime

I have a SQL Server function which converts a nvarchar day duration setting into a datetime value.
The day duration format is >days<.>hours<:>minutes<, for instance 1.2:00 for one day and two hours.
The format of the day duration setting can not be changed, and we can be sure that all data is correctly formatted and present.
Giving the function a start time and the day duration setting it should return the end time.
For instance: 2010-01-02 13:30 ==> 2010-01-03 2:00
I'm using a combination of charindex, substring and convert methods to calculate the value,
which is kind of slow and akward. Is there any other way to directly convert this day duration setting into a datetime value?
Not from what I can see. I would end up with a similar bit of SQL like you, using charindex etc. Unfortunately it's down to the format the day duration is stored in. I know you can't change it, but if it was in a different format then it would be a lot easier - the way I'd usually do this for example, is to rationalise the duration down to a base unit like minutes.
Instead of storing 1.2:00 for 1 day and 2 hours, it would be (1 * 24 * 60) + (2 * 60) = 1560. This could then be used in a straightforward DATEADD on the original date (date part only).
With the format you have, all approaches I can think of involve using CHARINDEX etc.
One alternative would be to build a string with the calculation. Then you can run the generated SQL with sp_executesql, specifying #enddate as an output parameter:
declare #startdate datetime
declare #duration varchar(10)
declare #enddate datetime
set #startdate = '2010-01-02 13:30'
set #duration = '0.12:30'
declare #sql nvarchar(max)
set #sql = 'set #enddate = dateadd(mi,24*60*' +
replace(replace(#duration,'.','+60*'),':','+') + ', #startdate)'
exec sp_executesql #sql,
N'#startdate datetime, #enddate datetime out',
#startdate, #enddate out
This creates a string containing set #enddate = dateadd(mi,24*60*0+60*12+30, #startdate) and then runs it.
I doubt this is faster than the regular charindex way:
declare #pos_dot int
declare #day int
declare #hour int
declare #minute int
select
#pos_dot = charindex('.',#duration),
#day = cast(left(#duration, #pos_dot-1) as int),
#hour = cast(left(right(#duration, 5), 2) as int),
#minute = cast(right(#duration, 2) as int),
#enddate = dateadd(mi, 24*60*#day + 60*#hour + #minute, #startdate)