MSSQL to MYSQL - Select from MSSQL , Insert into MySQL - mysql

Im trying to Establish a One Direction Sync from a specific query'd recordset from MSSQL (express 2008) to Mysql. Here is that query.
SELECT [datafk]
,[datahistorypk]
,[date]
,[displayText]
FROM [FCentral].[dbo].[DataHistory]
WHERE [sampleNr] =
(SELECT MAX (sampleNr) FROM [FCentral].[dbo].[DataHistory])
This results in a Multiple results. I need to insert each of those results into my "Linked Server" remotely connected MySQL DB Table.
This code works from SSMS and does insert into my MySQL DB.
EXEC (' INSERT INTO `farms`.`CCData` (
`datafk` ,`datahistorypk` ,`date` ,`displayText` )
VALUES ("222", "13", "2017-10-19 14:25:05", "TEST"); ')
at BPF_REMOTE
Ultimately i will need to schedule this query to run automatically, It would be nice if it could run if a change was detected in the MSSQL table but that may be outside of my abilities.
I feel like im close, im just struggling to get the syntax right to convert from MSSQL to MySQL. Can anyone either point to a good example or help me with this query?

Set up a linked server in SQL Server and just do a regular insert:
INSERT INTO BPF_REMOTE.farms.CCData(datafk, datahistorypk, date, displayText)
SELECT [datafk], [datahistorypk], [date], [displayText]
FROM [FCentral].[dbo].[DataHistory]
WHERE [sampleNr] = (SELECT MAX (sampleNr) FROM [FCentral].[dbo].[DataHistory]);

Related

Translate MySQL AES decrypt to Oracle SQL

Basically I'm stumped and thought I'd reach out to you hackers... I'm trying to convert this to something that would work in an Oracle Select statement. Tried Oracle crypto and still couldn't figure it out.
SET #key_str = FROM_BASE64('ZYXZYXYZXYZXYZXYZYX123123123');
SET #init_vector = UNHEX('ZYXZYXYZXYZXYZXYZYX124124124');
select person_id, CONVERT(AES_DECRYPT(FROM_BASE64(person_id), #key_str, #init_vector), CHAR) as id_decrypted from db.database_queried;```

Converting MS Access queries to MariaDB

I'm struggling to create MariaDB SQL commands which will produce the same output as these three queries (below) which I'm currently using with an MS Access database. My Excel VBA script calls the third SQL query command below (Hours to Heat Elecric WH) with only this SQL command, where the date value is substituted dynamically. For the purposes of this question that command would look like this:
SELECT ElectricWH_Data.*
FROM ElectricWH_Data
WHERE (ElectricWH_Data.Date_Reading) > #06/01/19#;
This is an abstract of the resulting table:
Date_Time Date Time Max WH Out Min WH Out
6/27/18 0:52 06/27/18 00.52 60.38 43.56
6/28/18 0:52 06/28/18 00.52 60.50 44.44
6/29/18 0:32 06/29/18 00.32 60.13 45.38
6/30/18 0:32 06/30/18 00.32 60.19 47.13
7/1/18 0:12 07/01/18 00.12 60.50 47.56
7/2/18 0:42 07/02/18 00.42 60.44 44.94
7/3/18 0:42 07/03/18 00.42 60.38 46.88
I would like to duplicate this process but using a MariaDB database and SQL commands. Can you assist?
By the way, I am aware that dates and date formats are handled differently in MariaDB.
Below are the SQL queries from the MS Access database.
GetTemDataByDay:
SELECT
Min(PiSolarWH.Electric_WH_Out) AS MinOfElectric_WH_Out,
Max(PiSolarWH.Electric_WH_Out) AS MaxOfElectric_WH_Out,
Format(PiSolarWH.Date_Reading,'mm/dd/yy') AS TheDay
FROM
PiSolarWH
GROUP BY
Format(PiSolarWH.Date_Reading,'mm/dd/yy');
ElectricWHData:
SELECT
PiSolarWH.Date_Reading,
Format([PiSolarWH.Date_Reading],'mm/dd/yy') AS TheDate,
Format([Date_Reading],'hh.mm') AS DayTime,
GetTempDataByDay.MaxOfElectric_WH_Out AS Expr1,
GetTempDataByDay.MinOfElectric_WH_Out AS Expr2
FROM
GetTempDataByDay, PiSolarWH
WHERE
Format([PiSolarWH.Date_Reading],'mm/dd/yy') = [GetTempDataByDay].[TheDay]
AND GetTempDataByDay.MaxOfElectric_WH_Out = [PiSolarWH].[Electric_WH_Out];
Hours to Heat Elecric WH:
SELECT
PiSolarWH.Date_Reading,
Format([Date_Reading],'hh.mm') AS DayTime,
GetTempDataByDay.MaxOfElectric_WH_Out,
PiSolarWH.Electric_WH_Out,
Format([PiSolarWH.Date_Reading],'mm/dd/yy') AS Expr1
FROM
GetTempDataByDay,
PiSolarWH
WHERE
GetTempDataByDay.MaxOfElectric_WH_Out = [PiSolarWH].[Electric_WH_Out]
AND Format([PiSolarWH.Date_Reading],'mm/dd/yy') = [GetTempDataByDay].[TheDay];
OK, I figured it out! MariaDB's stored VIEWS work like MS Access Stored Queries. I was able to add the three MS Access queries (of course with modified syntax) to the database as stored VIEWS. The work exacgtly like those in MS Access. Here is one example:
CREATE VIEW GetTempDataByDay AS
SELECT
date_reading,
Min(temps.Electric_WH_Out) AS MinOfElectric_WH_Out,
Max(temps.Electric_WH_Out) AS MaxOfElectric_WH_Out,
date(temps.Date_Reading) AS TheDay
FROM
temps
GROUP BY
date(temps.Date_Reading);
Which is then used in the other two VIEWS which I created to duplicate the MS Access stored queries.
Thanks for your time....RDK

SQL filling a table importing data from another table and math

I am trying to develop software for one of my classes.
It is supposed to create a table contrato where I would fill the info of the clients and how much are they going to pay and how many payments they will make to cancel the contract.
On the other hand I have another table cuotas which should be filled by importing some info from table1 and I'm trying to perform the math and save the payment info directly into the SQL. But it keeps telling me I cant save the SQL because of error #1241
I'm using PHPMyAdmin and Xampp
Here is my SQL code
INSERT INTO `cuotas`(`Ncontrato`, `Vcontrato`, `Ncuotas`) SELECT (`Ncontrato`,`Vcontrato`,`Vcuotas`) FROM contrato;
SELECT `Vcuotaunit` = `Vcontrato`/`Ncuotas`;
SELECT `Vcuotadic`=`Vcuotaunit`*2;
Can you please help me out and fix whatever I'm doing wrong?
Those selects are missing a FROM clause.
So it's unknown from which table or view they have to take the columns.
You could use an UPDATE after that INSERT.
INSERT INTO cuotas (Ncontrato, Vcontrato, Ncuotas)
SELECT Ncontrato, Vcontrato, Vcuotas
FROM contrato;
UPDATE cuotas
SET Vcuotaunit = (Vcontrato/Ncuota),
Vcuotadic = (Vcontrato/Ncuota)*2
WHERE Vcuotaunit IS NULL;
Or use 1 INSERT that also does the calculations.
INSERT INTO cuotas (Ncontrato, Vcontrato, Ncuotas, Vcuotaunit, Vcuotadic)
SELECT Ncontrato, Vcontrato, Vcuotas,
(Vcontrato/Ncuota) as Vcuotaunit,
(Vcontrato/Ncuota)*2 as Vcuotadic
FROM contrato;

SQL Server 2008: insert into table in batches

I have a linked server (Sybase) set up in SQL Server from which I need to draw data. The Sybase server sits on the other side of the world, and connectivity is pretty shoddy. I would like to insert data into one of the SQL Server tables in manageable batches (e.g. 1000 records at a time). I.e I want to do;
INSERT IN [SQLServerTable] ([field])
SELECT [field] from [LinkedServer].[DbName].[dbo].[SybaseTable]
but I want to fetch 1000 records at a time and insert them.
Thanks
Karl
I typically use python with the pyodbc module to perform batches like this against a SQL server. Take a look and see if it is an option, if so I can provide you an example.
You will need to modify a lot of this code to fit your particular situation, however you should be able to follow the logic. You can comment out the cnxn.commit() line to rollback the transactions until you get everything working.
import pyodbc
#This is an MS SQL2008 connection string
conn='DRIVER={SQL Server};SERVER=SERVERNAME;DATABASE=DBNAME;UID=USERNAME;PWD=PWD'
cnxn=pyodbc.connect(conn)
cursor=cnxn.cursor()
rowCount=cursor.execute('SELECT Count(*) from RemoteTable').fetchone()[0]
cnxn.close()
count=0
lastID=0
while count<rowCount:
#You may want to close the previous connection and start a new one in this loop. Otherwise
#the connection will be open the entire time defeating the purpose of performing the transactions in batches.
cnxn=pyodbc.connect(conn)
cursor=cnxn.cursor()
rows=cursor.execute('SELECT TOP 1000 ID, Field1, Field2 FROM INC WHERE ((ID > %s)) ' % (lastID)).fetchall()
for row in rows:
cursor.execute('INSERT INTO LOCALTABLE (FIELD1, FIELD2) VALUES (%s, %s)' % (row.Field1, row.Field2))
cnxn.commit()
cnxn.close()
#The [0] assumes the id is the first field in the select statement.
lastID=rows[len(rows)-1][0]
count+=len(rows)
#Pause after each insert to see if the user wants to continue.
raw_input("%s down, %s to go! Press enter to continue." % (count, rowCount-count))

Problem with SELECT * in MySQL through ODBC from Microsoft SQL Server

I have a MySQL server as a linked server in Microsoft SQL Server 2008. For the link I use MySQL ODBC Connector version 5.1.8. When invoking queries using OPENQUERY (the only way I found of performing queries), problems occur. Simple queries, such as
SELECT * FROM OPENQUERY(MYSQL, 'SHOW TABLES')
work fine. Selection of individual columns, e.g.,
SELECT * FROM OPENQUERY(MYSQL, 'SELECT nr FROM letter')
works fine as well, but SELECT * syntax does not work. The query:
SELECT * FROM OPENQUERY(MYSQL, 'SELECT * FROM mytable')
raises an error:
Msg 7347, Level 16, State 1, Line 6
OLE DB provider 'MSDASQL' for linked
server 'MYSQL' returned data that does
not match expected data length for
column '[MSDASQL].let_nr'. The
(maximum) expected data length is 40,
while the returned data length is 0.
How can I make the SELECT * syntax work?
This problem happens if you are querying a MySQL linked server and the table you query has a datatype char(). This means fixed length and NOT varchar(). This happens when your fixed length field has a shorter string than the maximum length that SQL Server expected to get from the ODBC.
To fix this go to your MySQL server and change the datatype to varchar() leaving the length as it is. Example change char(10) to varchar(10).
Executing the following command before queries seems to help:
DBCC TRACEON(8765)
The error messages go away and queries seem to be working fine.
I'm not sure what it does though; I found it here: http://bugs.mysql.com/bug.php?id=46857
Strangely, SQL Server becomes unstable, stops responding to queries and finally crashes with scary-looking dumps in the logs a few minutes after several queries to the MySQL server. I am not sure if this has to do anything with the DBCC command, so I'm still interested in other possible solutions to this problem.
What I did to fix this since I can't modify the MySQL database structure is just create a view with a cast ex: CAST(call_history.calltype AS CHAR(8)) AS Calltype,
and select my view from MSSQL in my linked server.
The reason behind is that some strange types don't work well with the linked server (in my case the MySQL enum)
I found this
"The problem is that one of the fields
being returned is a blank or NULL CHAR
field. To resolve this in the Mysql
ODBC settings select the option "Pad
CHAR to Full Length"
Look at the last post here
An alternative would be to use the trim() function in your SELECT statement within OPENQUERY. The downside is you have to list each field individually, but what I did was create a view that calls OPENQUERY and then perfrom select * on the view.
Not ideal, but better than changing data types on tables!
Here is a crappy solution I came up with because I am unable to change the datatype to varchar as the db admin for the MySQL server is afraid it will cause issues with his scripts.
in my MySQL select query I run a case statement checking the character length of the string and add a filler character in front of the string "filling it up" to the max (in my case its a char(6)). then in the select statement of the openquery I strip the character back off.
Select replace(gradeid,'0','') as gradeid from openquery(LINKEDTOMYSQL, '
SELECT case when char_length(gradeid) = 0 then concat("000000", gradeID)
when char_length(gradeID) = 1 then concat("00000", gradeID)
when char_length(gradeID) = 2 then concat("0000", gradeID)
when char_length(gradeID) = 3 then concat("000", gradeID)
when char_length(gradeID) = 4 then concat("00", gradeID)
when char_length(gradeID) = 5 then concat("0", gradeID)
else gradeid end as gradeid
FROM sometableofmine')
it works but it probably is slower...
maybe you can make a MySQL function that will do the same logic, or come up with a more elegant solution.
I had the similar problem to this myself, which I resolved by wrapping the column-names in single ` style quotes.
Instead of...
column_name
...use...
`column_name`
Doing this helps the MySql query-engine should the column-name clash with a key or reserved-word.*
Instead of using SELECT * FROM TABLE_NAME, try to use all column names with quotes:
SELECT `column1`, `column2`, ... FROM TABLE_NAME
Example for normal datatype columns
SELECT * FROM OPENQUERY(MYSQL, 'SELECT `column1`, `column2`,...,`columnN` FROM mytable')
Example for ENUM datatype columns
SELECT * FROM OPENQUERY(MYSQL, 'SELECT `column1`, trim(`column2`) `column2`, `column3`,...,`columnN` FROM mytable')
*For those used to Sql Server, it is the MySql equivalent of wrapping a value in square-brackets, [ and ].