Convert T-SQL to MySQL - mysql

Is there an easy way to convert Transact-SQL to MySQL?
I am attempting to convert a database archive of stock ticker symbols and company names.

The short answer: NO
The medium answer: MAYBE
The long answer: That depends on what's in your TSQL and how much time and effort you want to put into it.
TSQL is not a subset of MySQL's dialect. So there exists some TSQL for which there is no MySQL conversion. However, the overlap between the two languages is pretty significant, and to a certain degree the conversion is just a matter of syntax.
This isn't a new problem, and some people have tried to tackle it. A quick google search for "tsql to mysql" yields some promising results, notably this project here, which attempts to convert stored procedures from TSQL to MySQL:
http://sourceforge.net/projects/tsql2mysql/
This probably won't solve your problem completely, but it's at least a start.

This website converts to/from many sql database versions:
http://www.sqlines.com/online
TSQL, MySql, Oracle, DB2, Sybase, Informix, Hive, MariaDB, PostgreSQL, RedShift, TeraData, Greenplum, Netezza

Are the others say, it depends how long your particular piece of string is.
But, I would suggest that you do NOT want to convert Transact-SQL to MySQL.
If you think about it, I think that you will find that you want to convert it to ODBC.
And then next year, when the company wants you to move it to Oracle, or Access ...

I've just achieved a tsql script.
My solution is :
export table informations (schema pk)
export table data
export FK
I'm not very proud of my code, but it worked for me.
4 files wich are in the same folder:
Batch wich call sqlcmd
#echo off
set host= (local)
set schema=database
set user=user
set pass=pass
cd %cd%
rem tables
SQLCMD -S %host% -d %schema% -U %user% -P %pass% -s "" -h-1 -W -i "%CD%\mysql_export_table.sql" -o "%CD%\%schema%_tables.sql"
rem data
SQLCMD -S %host% -d %schema% -U %user% -P %pass% -s "" -h-1 -W -i "%CD%\mysql_export_data.sql" -o "%CD%\%schema%_data.sql"
rem fk
SQLCMD -S %host% -d %schema% -U %user% -P %pass% -s "" -h-1 -W -i "%CD%\mysql_export_fk.sql" -o "%CD%\%schema%_fk.sql"
then tsql script to export table schema mysql_export_table.sql
SET NOCOUNT ON;
SET QUOTED_IDENTIFIER ON;
DECLARE #table_name as varchar(max)
DECLARE view_cursor CURSOR FOR
SELECT Table_name FROM information_schema.tables where TABLE_TYPE = 'BASE TABLE' and table_name not like 'sys%'
OPEN view_cursor
FETCH NEXT FROM view_cursor
INTO #table_name
WHILE ##FETCH_STATUS = 0
BEGIN
select ''
select '/*** TABLE '+#table_name+' ***/ '
select 'DROP TABLE IF EXISTS ' + QUOTENAME(#table_name, '`') + ';'
select ''
select 'CREATE TABLE ' + QUOTENAME(#table_name, '`') + ' ('
-- column declaration
select
CHAR(9)
+ QUOTENAME(Column_Name, '`') + ' ' +
DATA_TYPE
+
coalesce( '(' + cast(coalesce(replace(CHARACTER_MAXIMUM_LENGTH, -1, 2500), null) as varchar) + ')', '')
+ ' ' +
case IS_NULLABLE WHEN 'NO' then 'NOT ' else '' end + 'NULL'
+ ' ' +
case when COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 then 'AUTO_INCREMENT' else '' end
--coalesce( 'DEFAULT ' + replace(replace(replace(COLUMN_DEFAULT, '(', ''), ')', ''), 'getdate', null), '')
+','
FROM information_schema.COLUMNS where TABLE_NAME = #table_name
-- PK
select coalesce('PRIMARY KEY (' +STUFF((
SELECT distinct ', ' + QUOTENAME(Col.Column_Name,'`') from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab inner join
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col on Col.Constraint_Name = Tab.Constraint_Name AND Col.Table_Name = Tab.Table_Name
WHERE
Constraint_Type = 'PRIMARY KEY '
AND Col.Table_Name = #table_name
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') , 1, 1, '')+ ')', '')
select ') Engine InnoDB;'
FETCH NEXT FROM view_cursor
INTO #table_name
END
CLOSE view_cursor;
DEALLOCATE view_cursor;
then script for data mysql_export_data.sql
SET NOCOUNT ON;
SET QUOTED_IDENTIFIER ON;
DECLARE #table_name as varchar(max)
declare #column_names as varchar(max)
DECLARE view_cursor CURSOR FOR
SELECT Table_name FROM information_schema.tables where TABLE_TYPE = 'BASE TABLE' and table_name not like 'sys%'
OPEN view_cursor
FETCH NEXT FROM view_cursor
INTO #table_name
WHILE ##FETCH_STATUS = 0
BEGIN
select ''
select '/*** TABLE '+#table_name+' ***/ '
select #column_names = STUFF(( SELECT ', ' + QUOTENAME(Column_Name, '`') from INFORMATION_SCHEMA.COLUMNS WHERE Table_Name = #table_name ORDER BY ORDINAL_POSITION FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') , 1, 1, '')
select 'REPLACE INTO '+ QUOTENAME(#table_name, '`') +'('+ #column_names+ ') VALUES '
select #column_names = 'SELECT DISTINCT ''('+ STUFF(( SELECT ', '','''''' + coalesce(replace(cast(' + QUOTENAME(Column_Name) +' as varchar(200)), '''''''',''''), '''') + ''''''''' from INFORMATION_SCHEMA.COLUMNS WHERE Table_Name = #table_name ORDER BY ORDINAL_POSITION FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') , 1, 4, '') + '+''),'' FROM ' + QUOTENAME(#table_name)
exec (#column_names)
FETCH NEXT FROM view_cursor
INTO #table_name
END
CLOSE view_cursor;
DEALLOCATE view_cursor;
Finally FK script
SET NOCOUNT ON;
SET QUOTED_IDENTIFIER ON;
-- FK
-- foreign keys
SELECT
'ALTER TABLE',
' '+ QUOTENAME(OBJECT_NAME(fkcol.[object_id]), '`'),
--ADD CONSTRAINT `recherche_ibfk_1` FOREIGN KEY (`notaire_compte_id`) REFERENCES `notaire_compte` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
' ADD CONSTRAINT',
' ' + QUOTENAME(fk.name, '`'),
' FOREIGN KEY',
' (' + QUOTENAME(fkcol.name, '`') +')',
' REFERENCES',
' ' + QUOTENAME(OBJECT_NAME(pkcol.[object_id]), '`'),
' (' + QUOTENAME(pkcol.name, '`') + ');',
CHAR(13)
FROM sys.foreign_keys AS fk
INNER JOIN sys.foreign_key_columns AS fkc
ON fk.[object_id] = fkc.constraint_object_id
INNER JOIN sys.columns AS fkcol
ON fkc.parent_object_id = fkcol.[object_id]
AND fkc.parent_column_id = fkcol.column_id
INNER JOIN sys.columns AS pkcol
ON fkc.referenced_object_id = pkcol.[object_id]
AND fkc.referenced_column_id = pkcol.column_id
ORDER BY fkc.constraint_column_id;
I know, i know... it's very ugly ...
The goal of this script is not to convert TSQL to Mysql but to export database from MSSQL to Mysql
On the table result you'll have to execute a regex replace (notepad++)
replace ",\r\n\r\n)" by "\r\n\r\n)"
On the data result replace ",\r\n\r\n/" by ";\r\n\r\n/"
Execution order : Table -> Data -> FK

How about using SQL Server Linked Servers ? You can SELECT, INSERT, UPDATE and DELETE data from MySQL using TSQL

Related

Mysql UNION with dynamic query

i have the following problem. I inherited a software that uses a database prefix for every customer.
All tables have the same structure and columns. For a data migration to new version i want to union all these tables
and set a customer foreign key instead and get rid of all the subtables. i'm looking for a way to create
a view for this task because i also want to stay backwards compatible for now.
I found this dynamic query which seems to do what i want
but i can't execute on my mysql server. I assume it was written for another sql server.
The table name structure is (about 80 customer tables):
customer1_faxe
customer2_faxe
customer3_faxe
customer4_faxe
...
How would you approach this problem?
DECLARE #SelectClause VARCHAR(100) = 'SELECT *'
,#Query VARCHAR(1000) = ''
SELECT #Query = #Query + #SelectClause + ' FROM ' + TABLE_NAME + ' UNION ALL '
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%_faxe'
SELECT #Query = LEFT(#Query, LEN(#Query) - LEN(' UNION ALL '))
EXEC (#Query)
This query is using SQL Server syntax. You need something like this:
declare #SelectClause varchar(8000);
declare #Query varchar(8000);
set #SelectClause = 'SELECT *';
SELECT #Query := group_concat(#SelectClause, ' FROM ', TABLE_NAME SEPARATOR ' UNION ALL ')
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%_faxe';
prepare stmt from #Query;
execute stmt;
Note that the group_concat() with separator simplifies the logic.

Alter all tables in database

I would like to run a "Alter Table" on ALL the tables in my SQL databse:
ALTER TABLE test ADD CONSTRAINT [COLLUM_NAME] DEFAULT ((0)) FOR [COLLUM_NAME]
I know how to get all of the existing tables from the database:
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
or
USE DATABASE_NAME
GO
SELECT name
FROM sys.Tables
GO
But I don’t know how to combine these two.
In my database (50+ tables) all of the tables have 1 row in common.
and I would like to set a default value to all of these rows.
You can try to generate a command and execute it after.
You can do something like this:
SELECT CONCAT("Alter Table `", TABLE_SCHEMA,"`.`", TABLE_NAME, "` this is my default value change on the column") as MySQLCMD
FROM TABLES
And execute the retrieving.
If this is a one-off process that doesn't need to be automated then you could probably do worse than running something like the following and just copy/pasting the output:
select 'alter table ' + t.name + ' add constraint ' + c.name + ' default ((0)) for ' + c.name
from sysobjects t join syscolumns c on c.id = t.id
where t.xtype = 'U'
If u want use INFORMATION_SCHEMA
SELECT 'ALTER TABLE ' +t.TABLE_NAME+ ' ADD CONSTRAINT '
+c.COLUMN_NAME +' DEFAULT ((0)) FOR '+c.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLES t
INNER JOIN INFORMATION_SCHEMA.COLUMNS c on t.TABLE_NAME=c.TABLE_NAME
WHERE TABLE_TYPE = 'BASE TABLE'
set the 'COLUMN NAME' and execute, it will add a default constraint to setted column.
DECLARE #sql NVARCHAR(MAX) ;
DECLARE #LINEBREAK AS VARCHAR(2)
SET #LINEBREAK = CHAR(13) + CHAR(10)
SELECT #sql = COALESCE(#sql + ';' + #LINEBREAK, '') + 'ALTER TABLE '
+ QUOTENAME([TABLES].TABLE_NAME) + ' ADD CONSTRAINT ' + QUOTENAME([COLUMNS].COLUMN_NAME)
+ ' DEFAULT ((0)) FOR ' + QUOTENAME([COLUMNS].COLUMN_NAME)
FROM INFORMATION_SCHEMA.TABLES [TABLES]
INNER JOIN INFORMATION_SCHEMA.COLUMNS AS [COLUMNS] ON [TABLES].TABLE_NAME = [COLUMNS].TABLE_NAME
WHERE TABLE_TYPE = 'BASE TABLE'
AND [COLUMNS].[COLUMN_NAME] = 'COLUMN NAME'
PRINT #sql
EXEC sp_executesql #sql
My preferred way is to write a SP for this. I have some of these utility SPs in my databases and I alter them as needed to update things. Here's an example that changes the collation. You can see that by modifying the SET #S=... statement you can do any table alteration you like.
DECLARE table_name VARCHAR(255);
DECLARE end_of_tables INT DEFAULT 0;
DECLARE num_tables INT DEFAULT 0;
DECLARE cur CURSOR FOR
SELECT t.table_name
FROM information_schema.tables t
WHERE t.table_schema = DATABASE() AND t.table_type='BASE TABLE';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET end_of_tables = 1;
OPEN cur;
tables_loop: LOOP
FETCH cur INTO table_name;
IF end_of_tables = 1 THEN
LEAVE tables_loop;
END IF;
SET num_tables = num_tables + 1;
SET #s = CONCAT('ALTER TABLE ' , table_name , ' CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci');
PREPARE stmt FROM #s;
EXECUTE stmt;
END LOOP;
CLOSE cur;

copy entire row (without knowing field names)

Using SQL Server 2008, I would like to duplicate one row of a table, without knowing the field names. My key issue: as the table grows and mutates over time, I would like this copy-script to keep working, without me having to write out 30+ ever-changing fields, ugh.
Also at issue, of course, is IDENTITY fields cannot be copied.
My code below does work, but I wonder if there's a more appropriate method than my thrown-together text string SQL statement?
So thank you in advance. Here's my (yes, working) code - I welcome suggestions on improving it.
Todd
alter procedure spEventCopy
#EventID int
as
begin
-- VARS...
declare #SQL varchar(8000)
-- LIST ALL FIELDS (*EXCLUDE* IDENTITY FIELDS).
-- USE [BRACKETS] FOR ANY SILLY FIELD-NAMES WITH SPACES, OR RESERVED WORDS...
select #SQL = coalesce(#SQL + ', ', '') + '[' + column_name + ']'
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'EventsTable'
and COLUMNPROPERTY(OBJECT_ID('EventsTable'), COLUMN_NAME, 'IsIdentity') = 0
-- FINISH SQL COPY STATEMENT...
set #SQL = 'insert into EventsTable '
+ ' select ' + #SQL
+ ' from EventsTable '
+ ' where EventID = ' + ltrim(str(#EventID))
-- COPY ROW...
exec(#SQL)
-- REMEMBER NEW ID...
set #EventID = ##IDENTITY
-- (do other stuff here)
-- DONE...
-- JUST FOR KICKS, RETURN THE SQL STATEMENT SO I CAN REVIEW IT IF I WISH...
select EventID = #EventID, SQL = #SQL
end
No, there isn't any magic way to say "SELECT all columns except <foo>" - the way you're doing it is how you'll have to do it (the hack in the other answer aside).
Here is how I would alter your code, with these changes (some are hyperlinked so you can read my opinion about why):
use sys.columns over INFORMATION_SCHEMA.COLUMNS
use nvarchar instead of varchar
use scope_identity instead of ##identity
use sp_executesql instead of exec
use stuff instead of coalesce
use SET NOCOUNT ON
add semi-colons
use the schema prefix
use QUOTENAME since it's safer than '[' + ... + ']'
ALTER PROCEDURE dbo.spEventCopy
#EventID INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX) = N'';
SELECT #sql += ',' + QUOTENAME(name)
FROM sys.columns
WHERE [object_id] = OBJECT_ID('dbo.EventsTable')
AND is_identity = 0;
SET #sql = STUFF(#sql, 1, 1, '');
SET #sql = N'INSERT dbo.EventsTable(' + #sql + ')
SELECT ' + #sql + ' FROM dbo.EventsTable
WHERE EventID = ' + CONVERT(VARCHAR(12), #EventID) + ';';
EXEC sp_executesql #sql;
SELECT #EventID = SCOPE_IDENTITY();
-- do stuff with the new row here
SELECT EventID = #EventID, SQL = #SQL;
END
If you know the what your identity column is called (and it won't be the column changing), you could do this:
SELECT * INTO #dummy FROM EventsTable where EventID = #EventID;
ALTER TABLE #dummy
DROP COLUMN MyIdentityColumn
INSERT EventsTable SELECT * FROM #dummy
DROP TABLE #dummy
Since a table can only every have one identity column, specifying that in the query shouldn't limit you too much.
As Aaron Bertrand points out, there are risks associated with this approach. Please read the discussion in the comments below.

sql update with dynamic column names

EDIT: Database names have been modified for simplicity
I'm trying to get some dynamic sql in place to update static copies of some key production tables into another database (sql2008r2). The aim here is to allow consistent dissemination of data (from the 'static' database) for a certain period of time as our production databases are updated almost daily.
I am using a CURSOR to loop through a table that contains the objects that are to be copied into the 'static' database.
The prod tables don't change that frequently, but I'd like to make this somewhat "future proof" (if possible!) and extract the columns names from INFORMATION_SCHEMA.COLUMNS for each object (instead of using SELECT * FROM ...)
1) From what I have read in other posts, EXEC() seems limiting, so I believe that I'll need to use EXEC sp_executesql but I'm having a little trouble getting my head around it all.
2) As an added extra, if at all possible, i'd also like to exclude some columns for particular tables (structures vary slightly in the 'static' database)
here's what i have so far.
when executed, #colnames returns NULL and therefore #sql returns NULL...
could someone guide me to where i might find a solution?
any advice or help with this code is much appreciated.
CREATE PROCEDURE sp_UpdateRefTables
#debug bit = 0
AS
declare #proddbname varchar(50),
#schemaname varchar(50),
#objname varchar(150),
#wherecond varchar(150),
#colnames varchar(max),
#sql varchar(max),
#CRLF varchar(2)
set #wherecond = NULL;
set #CRLF = CHAR(10) + CHAR(13);
declare ObjectCursor cursor for
select databasename,schemaname,objectname
from Prod.dbo.ObjectsToUpdate
OPEN ObjectCursor ;
FETCH NEXT FROM ObjectCursor
INTO #proddbname,#schemaname,#objname ;
while ##FETCH_STATUS=0
begin
if #objname = 'TableXx'
set #wherecond = ' AND COLUMN_NAME != ''ExcludeCol1'''
if #objname = 'TableYy'
set #wherecond = ' AND COLUMN_NAME != ''ExcludeCol2'''
--extract column names for current object
select #colnames = coalesce(#colnames + ',', '') + QUOTENAME(column_name)
from Prod.INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = + QUOTENAME(#objname,'') + isnull(#wherecond,'')
if #debug=1 PRINT '#colnames= ' + isnull(#colnames,'null')
--replace all data for #objname
--#proddbname is used as schema name in Static database
SELECT #sql = 'TRUNCATE TABLE ' + #proddbname + '.' + #objname + '; ' + #CRLF
SELECT #sql = #sql + 'INSERT INTO ' + #proddbname + '.' + #objname + ' ' + #CRLF
SELECT #sql = #sql + 'SELECT ' + #colnames + ' FROM ' + #proddbname + '.' + #schemaname + '.' + #objname + '; '
if #debug=1 PRINT '#sql= ' + isnull(#sql,'null')
EXEC sp_executesql #sql
FETCH NEXT FROM ObjectCursor
INTO #proddbname,#schemaname,#objname ;
end
CLOSE ObjectCursor ;
DEALLOCATE ObjectCursor ;
P.S. i have read about sql injection, but as this is an internal admin task, i'm guessing i'm safe here!? any advice on this is also appreciated.
many thanks in advance.
You have a mix of SQL and dynamic SQL in your query against information_schema. Also QUOTENAME isn't necessary in the where clause and will actually prevent a match at all, since SQL Server stores column_name, not [column_name], in the metadata. Finally, I'm going to change it to sys.columns since this is the way we should be deriving metadata in SQL Server. Try:
SELECT #colnames += ',' + name
FROM Prod.sys.columns
WHERE OBJECT_NAME([object_id]) = #objname
AND name <> CASE WHEN #objname = 'TableXx' THEN 'ExcludeCol1' ELSE '' END
AND name <> CASE WHEN #objname = 'TableYy' THEN 'ExcludeCol2' ELSE '' END;
SET #colnames = STUFF(#colnames, 1, 1, '');

SQL script to rebuild indexes - Incorrect syntax near the keyword 'Group'

I have a fairly basic SQL script to rebuild all the table indexes under various schema within a database. The script seems to work on the 183 indexes I have, but returns the error message
(183 row(s) affected)
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'Group'
Can anyone explain why and provide a solution?
USE RedGateMonitor;
GO
declare #db varchar(150)
declare #tmp TABLE(recnum int IDENTITY (1,1), tableschema varchar(150), tablename varchar(150))
insert #tmp (tableschema, tablename)
SELECT TABLE_SCHEMA, TABLE_NAME FROM information_schema.tables where TABLE_TYPE = 'BASE TABLE'
ORDER By TABLE_SCHEMA
declare #X int, #table varchar(150), #cmd varchar(500), #schema varchar(150)
set #X = 1
While #X <= (select count(*) from #tmp) BEGIN
set #db = 'RedGateMonitor'
set #table = (select tablename from #tmp where recnum = #X)
set #schema = (select tableschema from #tmp where recnum = #X)
set #cmd = 'ALTER INDEX ALL ON ' + #db + '.' + #schema + '.' + #table + ' REBUILD'
EXECUTE(#cmd)
set #X = #X + 1
END
I agree with both of Mitch's comments:
(1) you should be using an existing solution for this instead of reinventing the wheel.
(2) if you aren't going to follow basic rules for identifiers (e.g. not naming schemas or tables with reserved words), you need to properly escape them. A quick fix would be:
set #cmd = 'ALTER INDEX ALL ON ' + quotename(#db)
+ '.' + quotename(#schema)
+ '.' + Quotename(#table) +  ' REBUILD;';
A slightly better fix would be the following, with no need for #temp tables or looping:
DECLARE #sql NVARCHAR(MAX) = N'';
SELECT #sql += N'ALTER INDEX ALL ON ' + QUOTENAME(#db)
+ '.' + QUOTENAME(SCHEMA_NAME([schema_id])
+ '.' + QUOTENAME(name) + ' REBUILD;';
EXEC sp_executesql;
But I don't think you need to rebuild all of the indexes on all of the tables in the Red Gate database. Scripts like Ola's will help you be more efficient about which indexes to rebuild, which to reorganize, and which to leave alone.