Getting Error while executing SELECT statement in Toad for MySQL - mysql

I am getting this error while I am trying to execute a simple SELECT statement in Toad
MySql.Data.Types.MySqlConversionException
Unable to convert MySQL date/time value to System.DateTime
What could be wrong?

That could mean one of these two common issues:
1) Zero dates, which are 0000-00-00 in MySQL. MySQL allows you to store them to mark 0 dates, you can even use 0001-01-01, but not all drivers or downstream programs can handle them. Add to the connection string
Allow Zero Datetime=true;
The other choice is explicitly removing them, something like
SELECT IF(DateCol='0000-00-00' OR DateCol<'1970-01-01', NULL, DateCol) as DateCol,
Othercol1, ID ....
FROM TBL
2) Date formatting. For some driver/program combination, the dates are handled as strings. Explicit conversion is necessary:
SELECT DATE_FORMAT(DateCol, '%m/%d/%Y') as DateCol,
Othercol1, ID ....
FROM TBL

Related

Can't Set User-defined Variable From MySQL to Excel With ODBC

I have a query that has a user-defined variable set on top of the main query. Its something like this.
set #from_date = '2019-10-01', #end_date = '2019-12-31';
SELECT * FROM myTable
WHERE create_time between #from_date AND #end_date;
It works just fine when I executed it in MySQL Workbench, but when I put it to Excel via MySQL ODBC it always shows an error like this.
I need that user-defined variable to works in Excel. What am I supposed to change in my query?
The ODBC connector is most likely communicating with MySQL via statements or prepared statements, one statement at a time, and user variables are not supported. A prepared statement would be one way you could bind your date literals. Another option here, given your example, would be to just inline the date literals:
SELECT *
FROM myTable
WHERE create_time >= '2019-10-01' AND create_time < '2020-01-01';
Side note: I expressed the check on the create_time, which seems to want to include the final quarter of 2019, using an inequality. The reason for this is that if create_time be a timestamp/datetime, then using BETWEEN with 31-December on the RHS would only include that day at midnight, at no time after it.
Use subquery for variables values init:
SELECT *
FROM myTable,
( SELECT #from_date := '2019-10-01', #end_date := '2019-12-31' ) init_vars
WHERE create_time between #from_date AND #end_date;
Pay attention:
SELECT is used, not SET;
Assinging operator := is used, = operator will be treated as comparing one in this case giving wrong result;
Alias (init_vars) may be any, but it is compulsory.
Variable is initialized once but may be used a lot of times.
If your query is complex (nested) the variables must be initialized in the most inner subquery. Or in the first CTE if DBMS version knows about CTEs. If the query is extremely complex, and you cannot determine what subquery is "the most inner", then look for execution plan for what table is scanned firstly, and use its subquery for variables init (but remember that execution plan may be altered in any moment).

How to insert datetime into mysql from mssql with INSERT INTO OPENQUERY SELECT

I've been using the following format to insert into my mysql database previously, and would like to keep it uniform.
INSERT INTO OPENQUERY (ENET, 'SELECT * FROM ActiveDirectory.Computers') -- MYSQL database
SELECT c.[CommonName],
c.[DistinguishedName],
c.[SAMAccountName],
c.[DNSHostName],
c.[Location],
c.[Division],
c.[Department],
c.[ManagedBy],
c.[MachineRole],
CAST(CAST(c.[LastLogon] as timestamp) as datetime) AS LastLogon,
c.[OperatingSystem],
c.[OperatingSystemVersion],
c.[ServicePack],
c.[OU],
c.[CreatedOn],
c.[ChangedOn],
CASE WHEN c.[UserAccountControl] & 2 = 0 THEN 1 ELSE 0 END AS [Enabled] -- Check to see if disabled. Disabled = bitwise of 2; 4098 = 4096 + 2 = Trust Account + Disabled
FROM [IT_ActiveDirectory].[dbo].[ADComputerTable] c -- MSSQL database
My problem comes when inserting the fields that are datetimes in MSSQL (c.LastLogon, c.CreatedOn, c.ChangedOn) into mysql fields that are also datetimes. I have tried almost every combination of CAST() and CONVERT() I can think of, but I may have missed something. I have also tried changing mysql's field type to timestamp.
It returns: Conversion failed when converting date and/or time from character string.
It seems strange to me that MSSQL won't just send the data to MYSQL and let it do the conversion. Instead it looks like it is trying to convert and match the datatypes and data before it sends it to MYSQL.
If I can't insert it this way, I am open to another format, like if its possible to do the insert inside of the OPENQUERY() SELECT. Any suggestions? I'm dead in the water at the moment.
I would try to convert to ISO-8601 format string:
INSERT INTO OPENQUERY (ENET, 'SELECT * FROM ActiveDirectory.Computers')
SELECT
...,
CONVERT(VARCHAR, LastLogon, 126) AS LastLogon
FROM [IT_ActiveDirectory].[dbo].[ADComputerTable];
Also I don't like SELECT * in OPENQUERY. If columns are matched by position it is error-prone. Consider expanding start to columns.

sqlsrv find maximum from the table

Previously I was using the MySQL. With that I was able to use the query below to get the maximum number from the database.
Here 'No' is the varchar(10):
SELECT max(cast(No as unsigned)) as No FROM `tableName` LIMIT 1
The above query working fine in MySQL. I want to do the same thing in the MS SQL. When I run the same query, I get the following error:
Warning: sqlsrv_fetch_array() expects parameter 1 to be resource, boolean given
Any advice on this?
There is no LIMIT in SQL Server, no unsigned datatype, and no need to quote the table name.
Does this work:
SELECT max(cast(No as bigint)) as No FROM tableName

Date functions trim off timestamp in DB2

Is there a way to trim off the timestamp in a DB2 date function?
Have DB2 select statement where I'mm selecting a date form the databease and saving it to a variable. I then use that variable as a parameter for another db2 select by adding 30days to it but I don't think it agrees with the timestamp that it is adding to the end.
Select business_date From DB2INST1.BusDate Where key = 0
There is no timestamp in the database for this date but its adding '12:00:00AM' to the end
it saves this select into a variable and I use it in another select here
where expirdate > (DATE(#BusDate) + 30 DAYS)
I get this error:
{"ERROR [428F5] [IBM][DB2/AIX64] SQL0245N The invocation of routine \"DATE\" is ambiguous. The argument in position \"1\" does not have a best fit."} System.Exception {IBM.Data.DB2.DB2Exception}
Select business date as a varchar/string
Select varchar_format(business_date,'YYYY-MM-DD')
then do this to use it later, convert it to a date then use a date function to add 30days to it:
(DATE(to_date(#BusDate, 'YYYY-MM-DD') + 30 DAYS))
Try
where expirdate > DATE(#BusDate + 30 DAYS)
Is the first SELECT statement and the second SELECT Statement part of same stored procedure? Are you storing the resulting date in any .Net variable? If you are storing it in a .Net DateTime variable, my suggestion is to do the date addition operation in .Net code itself. And then remove the time part from the variable before passing to the database.
Take a look at this too: Datetime field overflow with IBM Data Server Client v9.7fp5
If both the SELECT statements were part of a stored procedure and there is no .Net DateTime variable invloved, then it is a different story.

Find invalid dates in SQL Server 2008

I have a 300.000 rows table; one of the columns is a varchar() but it really contains a date xx/xx/xxxx or x/x/xxxx or similar. But executing the following test yields an error:
SELECT CAST(MyDate as Datetime) FROM MyTable
The problem is that it doesn’t tell me in which row…
I have executed a series of “manual” updates by trial an error and performed simple updates to fix those, but there’s got to be some weird values that need to either be deleted or fixed.
For example I performed a simple test that fixed about 40 rows:
UPDATE MyTable SET MyDate = REPLACE(MyDate, '/000','/200') FROM MyTable WHERE MyDate like ('%/000%’)
UPDATE MyTable SET MyDate = REPLACE(MyDate, '/190','/199') FROM MyTable WHERE MyDate like ('%/190%’)
This fixed quite a few weird rows that had dates like 01/01/0003 and such. (Dates range from 1998 to 2010).
However, I’d like to know which rows are failing in the above select.
What would be the best way to print those so I can either delete them, edit them or see what to do? Thanks.
SELECT
*
FROM
MyTable
WHERE
ISDATE(MyDate) = 0
From the ISDATE(Transact-SQL) documentation ISDATE(...)
Returns 1 if the expression is a valid datetime value; otherwise, 0.
ISDATE returns 0 if the expression is a datetime2 value.
Did you try the ISDATE function?
Careful with IsDate. I have 1 bad record in a table of thousands. It says 8201-11-30 is a valid date. IsDate should have a YEAR limitation.
ISDATE doesn't seem to be working always.
the following returns 1 in SQL server 2008 R2
Select ISDATE('04- December 20')
But trying to cast the same value to date will fail.
Select cast('04- December 20' as date)
Conversion failed when converting date and/or time from character string.