Date and/or time from character string error message - sql-server

SELECT communication.*
,employeedetails.resourcename
FROM communication
,employeedetails
WHERE employeedetails.employeenumber = communication.employeenumber
AND communication.project = employeedetails.projectname
ORDER BY
CONVERT(DATETIME ,communication.month ,5)
I am getting the following error message:
"Conversion failed when converting date and/or time from character
string"
Kindly help me out

It is not easy having no info regarding the data tables involved!
However if names are meaningful, how can you convert a month to a datetime?
If it is existing try this:
SELECT communication.*, employeedetails.resourcename
FROM communication, employeedetails
WHERE employeedetails.employeenumber = communication.employeenumber and communication.project = employeedetails.projectname
ORDER BY communication.day, communication.month, communication.year --due to style 5
even if I would suggest to go for style 12

The datatype of communication.month is presumably a character type. If this holds "January" for January etc. then SQL has no way of converting that character to a datetime. You would need to append a string such that SQL could parse it as a datetime.
e.g. ORDER BY CONVERT(datetime,communication.month + '01 2000',5).
However, storing the communication date as a datetime in the first place would be better...

Related

T SQL Conversion failed when converting date and/or time from character string from VARCHAR(MAX)

I'm using SQL Server 2014. I have a date stored as varchar(MAX) in the format of:
2019-02-18
However, I want it in the British format dd/mm/yyyy (103).
This is my SQL:
SELECT CONVERT(DATE, DateField, 103) AS "JobStartDate"
FROM tblTest
However, I keep getting this error:
Conversion failed when converting date and/or time from character string.
What am I missing?
Update: The date is initially stored as varchar max as it is coming from a 3rd party system. I have no control over this and I completly understand this is the wrong format, but this is what I have been given.
I have a date stored as varchar(MAX)
There's your problem right there.
Not only you are using the wrong data type to store dates, you are also using max which is a known performance killer.
The solution to the problem is to alter the table and store dates in a Date data type - but first, you must look up all the objects that depends on that column and make sure they will not break or change them as well.
Assuming this can't be done, or as a temporary workaround, you must first convert the data you have to Date, and then convert it back to a string representation of that date using the 103 style to get dd/mm/yyyy.
Since yyyy-mm-dd string format is not culture dependent with the date data type, you can simply do this:
SELECT CONVERT(char(10), TRY_CAST(DateField As Date), 103) As [JobStartDate]
FROM tblTest
Note I've used try_cast and not cast since the database can't stop you from storing values that can't be converted to dates in that column.
You want to format the DateField column and not convert it to date.
So first convert it to DATE and then apply the format:
SELECT FORMAT(CONVERT(DATE, DateField, 21), 'dd/MM/yyyy') AS JobStartDate
See the demo.

Conversion failed when converting date and/or time from character string during update only

I have been searching for a resolution for a long time now and just can't seem to formulate a query that brings back the resolution so as a last resort I have posted here.
I have a SQL server table with a varchar column that has the date and time stored in this format
"1/1/2013 11:38:31 PM Some other text"
I needed this date and time portion of this data to be stored in another column in datetime datatype. So I created a new column called DateTimeLog of type datetime.
I then used left to chop off the extra text and convert to change the value to datetime format and got the result I would expect.
select CONVERT(DATETIME,(rtrim(left(olddate, 21)))) from mytable
results:
"2013-01-01 23:38:31.000"
So far, so good. this is what I would expect. My troubles begin when I attempt to update my new datetime column with the results of this CONVERT statement.
update mytable
SET DateTimeLog = CONVERT(DATETIME,(rtrim(left(olddate, 21)))) from mytable
I get the infamous "Conversion failed when converting date and/or time from character string" error message.
Conversion failed when converting date and/or time from character string.
I have also attempted to use cast
update mytable
SET DateTimeLog = (cast(CONVERT(DATETIME,(rtrim(left(oldtable, 21)))) as datetime)) from mytable
the error persists. As best I can tell the convert is working correctly because I can see the result set from a select, but getting that result into a new column has eluded me thus far.
thanks,
Your string isn't going to consistently be 21 characters long. Your sample data shows a single character month and a single character date. What if it's, say, 12/13/2018?
That said, you need a more robust way to isolate that timestamp. I used a PATINDEX to capture the position of the last colon in the time component, with a couple of regexes in there to account for the numbers & the AM/PM thing. Then I added 6 to it to get to the end of the string of interest.
This seems to work:
DECLARE #t TABLE (olddate VARCHAR(100));
INSERT #t
(
olddate
)
VALUES
('12/13/2018 11:38:31 PM Some other text')
,('1/1/2018 11:38:31 PM Some other text');
SELECT CAST(LEFT(olddate,PATINDEX('%:[0-9][0-9] [AP]M%', olddate)+6) AS DATETIME)
FROM #t;
Results:
+-------------------------+
| 2018-12-13 23:38:31.000 |
| 2018-01-01 23:38:31.000 |
+-------------------------+
Rextester: https://rextester.com/BBPO51381 (although the date format's a little funky on the output).

Load the date separated by '/' with the Datetime datatype in sql server

INSERT INTO PUZ_DATE_FORMAT
SELECT FORMAT(GETDATE(),'d', 'it-IT') AS ItalianDate
I get this error:
Msg 242, Level 16, State 3, Line 1
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
My table contains only a single column of datetime datatype, and the format statement which I've written will give the output like 15/12/2017.
But when I try to insert a row into the table, it won't allow me to do so. It allows only dd-mm-yyyy format - not dd/mm/yyyy. Why?
Basically what you are trying to do is insert a string value to a Datetime field. In doing so, SQL Server try to cast the string to a datetime during the insert. If your string is in the Universal format (yyyy-MM-dd) it can successfully parse it without any issue. Else the string has to be in the datetime format as Server's culture.
I guess your Server's culture is en-US which has the date time format as "MM/dd/yyyy". With regarding to your date (15/12/2017) server thinks 15 is the month, 12 is the day and so on. Which is obviously falling.
If you tried this before 12th of the month, It can successfully cast, But to an incorrect value.
Further, you are not doing the right thing by, casting a Datetime to a string and then try to insert in to Datetime field. Try to store the raw Datetime in database and format accordingly when displaying in UIs.
Cheers,

Allow Search for Invalid Date stored as string - Is it recommended or not

I have two tables for an Entity - say Valid_Doc and Invalid_Doc. If document is valid, then all the data gets saved in Valid_Doc table.In case any of the attribute of document is invalid , it gets saved in Invalid_Doc.Due_Date is on of the column of both the tables. In Invalid_Doc , we are saving Invalid dates as string.
Suppose if user searches for documents through a SEARCH screen with following date
Due_Date - is after - 07/07/11,
Shall we show all the documents from both the tables.As Due_Date in Invalid_Doc table is string, there is no way we can compare the entered search date with the dates available in database in Invalid_Doc table.
Can someone please guide me whether to use DATEDIFF - i.e. need to convert the String date in DB to Date(millisecs) first and then do the comparison with the entered data.Doing this , there may be unpredictable results. So , shall we allow the user to search for Invalid doc through Date or NOT.
Select * FROM invalid_doc iil WITH (nolock) WHERE
CAST(Datediff(s, '19700101 05:00:00:000', iil.due_date) AS NUMERIC) *
1000
BETWEEN '1120501800000' AND '1120501800000'
Where '1120501800000' and '1120501800000' are Date converted in milliseconds.
Please suggest.
I would convert the dates in the database to a uniform string format using regex (eg. Q20011231Q) and also convert the query to the same format before searching.
This way you would have control on your data and can easily do comparisons
I continue as answer :)
As I don't know your language you handle the xml data I strongly suggest you validate you date befor you insert into your database.
It is not possible to enter a non valid data value into a datatime field.
if you have a data like 11/24/2011 and insert it, the datetime value always add the time itself.
Then you have eg. 11/24/20011 17:29:00 000 as value stored.
If you insert less then a date it might crash or if the value can be converted to a valid date, the missing parts will be replaced by "current date information".
So in fact you have to validate you string, convert it. Something like this:
-- #datestring <= somehow your string from xml
SET arithabort arith_overflow OFF
SET #date = CAST(#datestring AS DATETIME)
IF #date is NULL SET #date = GETDATE()
SET arithabort arith_overflow ON
You turn overflow error mode off, try convert and set default if it fails.
Or in MS SQL
IF ( ISDATE(#date_string) = 0 ) SET #date = GETDATE()
Hope this helps

C, unixODBC, oracle and Date queries

I've got a query like
select x from tableName where startDate <= now;
When i query the database without the date fields, everything works as expected. As soon as i start using date or timestamp columns in the oracle Database, my queries return nothing or an error.
What I do:
snprintf(sql, sizeof(sql), "SELECT roomNo, userPass, adminPass, adminFlags, userFlags, bookId, is_locked, running_on_server FROM booking WHERE roomNo = '?' AND startTime <= { ts '?' } AND endTime >= { ts '?' } for update;");
stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
the ? will be replaced by values, with following command:
SQLBindParameter(stmt, i + 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(gps->argv[i]), 0, gps->argv[i], 0, NULL);
when I execute the query I get an error that TS is an invalid identifier [this was a recommendation by another board, taken from msdn - which may cause this error]
but even if I remove it and send just a string to the database, I'll get an empty result back. I also tried to bind the parameters as SQL_TIMESTAMP and SQL_DATE, but this didn't help either.
Hopefully somebody can help me.
thanks in advance.
Chris
Are you sending a DATE data type to the Oracle query or a date represented in a string?
From the Oracle side of things, if you send a date in a string variable you'll need to use the oracle "TO_DATE" function (http://www.techonthenet.com/oracle/functions/to_date.php) to then convert thew string back to a date for use in your SQL statement (assuming startDate or startTime/endTime are DATE columns in the database).
Your fist SQL example should be:
SELECT x
FROM tableName
WHERE startDate <= TO_DATE(now, '<date-format>');
If the variable "now" was a string containing '05-OCT-2011 16:15:23' (including a time portion) then the to_date would be:
TO_DATE(now, 'DD-MON-YYYY HH24:MI:SS')
If you compare a string with a date and don't specify the format of that date Oracle will use its default NLS parameters and try to apply that format. Therefore it is always prudent to specify the date format using TO_DATE.
Hope it helps...

Resources