Convert SQL Server stored procedure to MySQL - mysql

I need to convert the following stored procedure of SQL Server to MySQL. I am new to MySQL.
CREATE PROC InsertGenerator
(#tableName varchar(100)) as
--Declare a cursor to retrieve column specific information
--for the specified table
DECLARE cursCol CURSOR FAST_FORWARD FOR
SELECT column_name,data_type FROM information_schema.columns
WHERE table_name = #tableName
OPEN cursCol
DECLARE #string nvarchar(3000)
--for storing the first half
--of INSERT statement
DECLARE #stringData nvarchar(3000)
--for storing the data
--(VALUES) related statement
DECLARE #dataType nvarchar(1000) --data types returned
--for respective columns
SET #string='INSERT '+#tableName+'('
SET #stringData=''
DECLARE #colName nvarchar(50)
FETCH NEXT FROM cursCol INTO #colName,#dataType
IF ##fetch_status<>0
begin
print 'Table '+#tableName+' not found, processing skipped.'
close curscol
deallocate curscol
return
END
WHILE ##FETCH_STATUS=0
BEGIN
IF #dataType in ('varchar','char','nchar','nvarchar')
BEGIN
SET #stringData=#stringData+'''''''''+
isnull('+#colName+','''')+'''''',''+'
END
ELSE
if #dataType in ('text','ntext')
--if the datatype
--is text or something else
BEGIN
SET #stringData=#stringData+'''''''''+
isnull(cast('+#colName+' as varchar(2000)),'''')+'''''',''+'
END
ELSE
IF #dataType = 'money' --because money doesn't get converted
--from varchar implicitly
BEGIN
SET #stringData=#stringData+'''convert(money,''''''+
isnull(cast('+#colName+' as varchar(200)),''0.0000'')+''''''),''+'
END
ELSE
IF #dataType='datetime'
BEGIN
SET #stringData=#stringData+'''convert(datetime,''''''+
isnull(cast('+#colName+' as varchar(200)),''0'')+''''''),''+'
END
ELSE
IF #dataType='image'
BEGIN
SET #stringData=#stringData+'''''''''+
isnull(cast(convert(varbinary,'+#colName+')
as varchar(6)),''0'')+'''''',''+'
END
ELSE
--presuming the data type is int,bit,numeric,decimal
BEGIN
SET #stringData=#stringData+'''''''''+
isnull(cast('+#colName+' as varchar(200)),''0'')+'''''',''+'
END
SET #string=#string+#colName+','
FETCH NEXT FROM cursCol INTO #colName,#dataType
END

http://dev.mysql.com/doc/refman/5.0/en/stored-routines-syntax.html
This link contains the documentation on creating stored procedures and functions in MySql. You have quite a lot of code there so it may come down to 6 of 1 and half dozen of the other.

You can convert it to MySQL by using the following steps.
In SQL Server the parameters of the stored procedure are declared as
For Example:
CREATE PROCEDURE Strproc_example(
#strBillingPeriodID VarChar(200),
#result int OUT)
In MySQL it is
CREATE PROCEDURE Strproc_example(
v_strBillingPeriodID VarChar(200),
OUT v_result int )
In SQL server there is the As keyword. Remove that in MySQL
Then put a semicolon after in statement of SQL Server to convert it
into MySQL statements.

Related

Stored procedure to fetch entire row from database

I am a beginner to MYSQL and currently practicing stored procedures. I am trying to create a procedure that should fetch a row of an entire field when given an input parameter. Is there any workaround for this? If yes, then it would be an immense help.
Many Thanks
Welcome to the Forum.
A stored procedure can simple consist of a SELECT statement that returns all the columns in the row you want. e.g.
CREATE PROCEDURE `myproc`(IN `p_id` INT(11))
READS SQL DATA
SELECT id, COL2, COL3, ETC
FROM `mytable`
WHERE id = 'p_id';
If you need to traverse a table, looking at every row that meets some criteria, then you need to DECLARE a "cursor", and use that to fetch the rows you want. Here is a template I use to create new procedures that need to traverse a table - it can be adapted to suit your needs. In this template I nly retrieve two columns from the cursor, but you can retrieve any number. You have to declare a local variable for each column in your SELECT so the FETCH statement has somewhere to put the data it retrieves from the cursor:
CREATE PROCEDURE `traverse_table`()
READS SQL DATA
BEGIN
DECLARE var_id INT(11) UNSIGNED;
DECLARE var_data varchar(16383);
DECLARE done INT DEFAULT FALSE;
DECLARE ecode varchar(1000) ;
DECLARE emsg varchar(1000) ;
DECLARE nextrecord CURSOR FOR # here is the CURSOR DECLARATION
SELECT `myid`,`mydata` # It will return these rows, one
FROM `mytable` # at a time
WHERE `mydata` LIKE "ABC%";
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1 ecode = RETURNED_SQLSTATE, emsg = MESSAGE_TEXT;
SELECT var_id,var_data,ecode,emsg;
END;
OPEN nextrecord;
FETCH nextrecord into var_id,var_data; # here is the first Fetch
WHILE (done = FALSE) DO
# >>>>>> do something with var_id,var_data here <<<<<<
SET done = FALSE;
FETCH NEXT FROM records into var_id,var_data; # here is the second and subsequent Fetch
END WHILE;
CLOSE nextrecord;
END

Declare is not valid at this position, expecting

Have Declares which are giving unbefore seen errors, that have attempted to find the solution of. As well as weird as have previous procedures which use same syntax but do not throw any errors
This is for a procedure which uses cursors to retrieve information from a table, then insert it into another table, which is done so that the information within may be used to be able calculate a total, which is passed along along with some required values
BEGIN
DECLARE fin INT DEFAULT FALSE;
DECLARE pol VARCHAR(30) default '';
DECLARE total_accrued decimal(20,2) DEFAULT '0.00';
DECLARE total_paid decimal(20,2) DEFAULT '0';
DECLARE TOTAL DECIMAL(20,2) DEFAULT '0.00';
DECLARE user_pol varchar(45) default '';
DECLARE c3 CURSOr FOR SELECT total_accrued FROM fn_policy_mast;
DECLARE c4 CURSOR FOr SELECT total_amount_paid FROM fn_policy_mast;
DECLARE c2 CURSOR FOR SELECt policy_number FROM fn_policy_mast;
DECLARE c1 CURSOr FOR SELECT balance FROM fn_policy_mast;
-- DECLARE d_policy CURSOR FOR SELECT DISTINCT cod_policy FROM fn_policy_mast;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET fin = TRUE;
OPEN c1;
OPEN c2;
OPEN c3;
OPEN c4;
-- OPEN d_policy;
read_loop: LOOP
FETCH c3 INTO total_accrued;
FETCH c4 INTO total_paid;
FETCH c2 INTO pol;
set total = 0;
-- FETCH d_policy INTO user_pol;
-- IF user_pol = pol then
set total_accrued = (SELECT SUM(monthly_premium) FROM col_trans_log WHERE policy_number LIKE pol);
set total_paid = (SELECT SUM(transaction_amount) FROM col_Trans_log WHERE policy_number LIKE pol);
set total = total_paid - total_accrued;
-- END IF;
-- set TOTAL = (total_accrued-total_paid);
UPDATE fn_policy_mast set balance = TOTAL WHERE policy_number like pol;
IF fin=TRUE THEN
LEAVE read_loop;
END IF;
-- INSERT STATEMENTS HERE
-- set total = 0;
END LOOP;
select * FROM fn_policy_mast;
close c1;
close c2;
CLOSE c3;
CLOSE c4;
END//
DELIMITER ;````
Expected result to run, accepting the declares, actual experience is thaere is some form of syntax wrong, as it does not properly recognise the declare statements
This is the error message : Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5
DECLARE total_paid decimal(20,2) DEFAULT '0'
Is this the line?
Have you tried changing the default to '0.00' ?
Sorry guys, I made a dumb mistake and forget to include the delimiter before the procedure, afterwards it works.
Simply include a "Delimiter //" before the procedure
However, a stored procedure consists of multiple statements separated by a semicolon (;).
If you use a MySQL client program to define a stored procedure that contains semicolon characters, the MySQL client program will not treat the whole stored procedure as a single statement, but many statements.
Therefore, you must redefine the delimiter temporarily so that you can pass the whole stored procedure to the server as a single statement.
DELIMITER $$
CREATE PROCEDURE sp_name()
BEGIN[enter link description here][1]
-- statements
END $$
DELIMITER ;
Please refer attached link for more detail.

Error Syntax on Mysql Function

Would like to know what is the error on this syntax since all the sample given is similar with the 1 i try to create
CREATE FUNCTION test(regionCode varchar(5)) RETURNS CHAR(50)
DETERMINISTIC
READ SQL DATA
BEGIN
DECLARE NAME_FOUND CHAR(50);
SELECT 'abc' into NAME_FOUND from dual;
RETURN NAME_FOUND;
END
Thanks for the help.
mysql Functin having only READS SQL DATA not READ SQL DATA,that is the mistake you have done in your function.Please find the link for more details:
https://dev.mysql.com/doc/refman/5.7/en/stored-programs-logging.html
READS SQL DATA explicitly tells to MySQL that the function will ONLY read data from databases, thus, it does not contain instructions that modify data, but it contains SQL instructions that read data (e.q. SELECT).
DELIMITER $$
CREATE FUNCTION test(regionCode varchar(5)) RETURNS CHAR(50)
DETERMINISTIC
READS SQL DATA
BEGIN
DECLARE NAME_FOUND CHAR(50);
SELECT 'abc' into NAME_FOUND from dual;
RETURN NAME_FOUND;
END
CREATE FUNCTION test(regionCode varchar(5)) RETURNS CHAR(50)
READS SQL DATA
DETERMINISTIC
BEGIN
DECLARE NAME_FOUND CHAR(50);
SELECT 'abc' into NAME_FOUND from dual;
RETURN NAME_FOUND;
END
TRY THIS QUERY

mysql stored procedure variable error

Hi I am finding my way round MySQL trying to migrate data from MSsql for the first time. I have created a stored procedure that clear all the tables down so I can import the data repeatedly as I test and alter things. I thought I had this pretty well figured but I am unsure how to get the actual value of the variable to go with the delete statement. Thanks for any assistance
DELIMITER $$
CREATE PROCEDURE ClearData ()
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE v_TableName varchar(100) DEFAULT "";
-- declare cursor for list of tables to clear
DEClARE TableToRemove CURSOR FOR
SELECT TABLE_NAME from information_schema.tables where table_type ='BASE TABLE';
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET v_finished = 1;
OPEN TableToRemove;
ClearData: LOOP
FETCH TableToRemove INTO v_TableName;
IF v_finished = 1 THEN
LEAVE ClearData;
END IF;
--This is the problem how do I get the value of v_TableName
delete from `v_TableName`;
END LOOP ClearData;
CLOSE TableToRemove;
END$$
DELIMITER ;

MySQL 5.6 Declare Issue

Let's see if I can edit this and put the whole procedure in.
I am trying to convert an Oracle database to MySQL. I have all the tables, keys, indexes, and views converted. I now need to convert a stored procedure to MySQL.
I have most of it done, and there is only one hang up on my code:
set dns1_tmp = X.X.X.X;
SET dns2_tmp = X.X.X.X;
This gives me an error of 1064 Syntax Error: Missing semicolon
I have tested the rest of my procedure, and it works fine. It creates it, runs it, and retrieves data from it, but only if I remove those two lines.
Any ideas on what I can do?
Whole stored procedure:
DELIMITER //
USE `TEST`//
DROP PROCEDURE IF EXISTS `proc_IN`//
CREATE DEFINER=`root`#`localhost` PROCEDURE `proc_IN`
(IN DNIS VARCHAR(20),
IN MSISDN VARCHAR(20),
IN AVPAIR1 VARCHAR(20),
IN AVPAIR2 VARCHAR(20),
IN GROUPID VARCHAR(20),
OUT DNS1 VARCHAR(15),
OUT DNS2 VARCHAR(15),
OUT AUTHSTAT VARCHAR(100))
BEGIN
declare dns1_tmp varchar(15);
declare dns2_tmp varchar(15);
set dns1_tmp = X.X.X.X;
SET dns2_tmp = X.X.X.X;
DECLARE avpair1_tmp varchar(15);
DECLARE avpair2_tmp varchar(15);
DECLARE grpid_tmp varchar(15);
DECLARE C_USER CURSOR FOR SELECT AVPAIR1, AVPAIR2, DNS1, DNS2, GROUPID FROM GRP, ALLMEMBER WHERE ALLMEMBER.GROUPID=GRP.GROUPID
UNION
SELECT AVPAIR1, AVPAIR2, DNS1, DNS2, GROUPID FROM GRP;
OPEN C_USER;
FETCH C_USER INTO AVPAIR1, AVPAIR2, DNS1, DNS2, GROUPID;
LOOP
FETCH C_USER INTO avpair1_tmp, avpair2_tmp, dns1_tmp, dns2_tmp, grpid_tmp;
INSERT INTO duplog VALUES(DNIS, MSISDN, avpair1_tmp, avpair2_tmp, dns1_tmp,dns2_tmp, grpid_tmp, SYSDATE);
END LOOP;
IF C_USER%ROWCOUNT > 1 THEN
INSERT INTO duplog VALUES(DNIS, MSISDN, AVPAIR1, AVPAIR2, DNS1,DNS2, GROUPID, SYSDATE);
SET AUTHSTAT := 'ok';
elseif C_USER%ROWCOUNT = 1 THEN
SET AUTHSTAT := 'ok';
ELSE
SET AUTHSTAT := NULL;
END IF;
CLOSE C_USER;
COMMIT;
END //
DELIMITER ;