views:

730

answers:

1

Trying to migrate from MSSQL to MySQL. This Stored Proc is creating a temp table for some columns from a permanent table then using a cursor to update each record's RandNum column with a random number and selects the dataset. As I'm writing this I thought that I could bypass the cursor and just...

SELECT Id, Title, DateStart, Rand() FROM cms_News;

But i dont want to change anything too drastic, because right now I'm just trying to convert the DB. I will go back and optimize this stuff later. Here's the SP: EDIT: I removed all of the code from this example that has nothing to do with the error. Also, I saw this online today and it seems that I'm not the only one who is having this issue. MySQL does not like the syntax of my cursor declaration. Any Ideas?

DELIMITER ;//

DROP PROCEDURE IF EXISTS `cms_NewsSelectMainPageNews`;//
CREATE PROCEDURE `cms_NewsSelectMainPageNews`
()
BEGIN
  CREATE TEMPORARY TABLE tempNews
  (
    Id int NOT NULL, 
    Title nvarchar(250),
    DateStart datetime,
    RandNum float NULL
  );

  DECLARE Randomizer CURSOR
      FOR SELECT Id FROM tempNews;
END;//
A: 
  REPEAT
    FETCH Randomizer INTO cursor_id;
    IF NOT done THEN
      UPDATE tempNews SET RandNum = rand();
       WHERE id = @cursor_id;
    END IF;
  UNTIL done END REPEAT;

You are using unitialized session variable @cursor_id instead of procedure-declared variable cursor_id

Rewrite as follows:

  REPEAT
    FETCH Randomizer INTO cursor_id;
    IF NOT done THEN
      UPDATE tempNews SET RandNum = rand();
       WHERE id = cursor_id;
    END IF;
  UNTIL done END REPEAT;

or even better, just get rid of your temporary table at all, as you suggested in the first place.


As for this statement:

But i dont want to change anything too drastic, because right now I'm just trying to convert the DB. I will go back and optimize this stuff later.

SQL Server and MySQL are vastly different platforms.

You've already changed everything too drastic when decided to switch.

In most cases you can't just copy your old code and hammer it to MySQL.

It would possibly work between several versions of SQL Server, since at least there are attempts to maintain some kind of compatibility between the versions of same platform, but this definitely won't work for porting to MySQL.

What I would do is take every piece of your code and make sure it produces the same results as the old code did, using methods as simple and predictable as possible.

In your case, the @cursor_id variable could be initialized earlier in the code and its value could be used by the stored procedure, which would lead to any kind of unexpected behaviour.

This is because in SQL Server the variables have batch scope, while in MySQL they have session scope.

Quassnoi
This isn't what's breaking it, although this raises another question which you can answer if you wish: http://stackoverflow.com/questions/1009954/mysql-variable-vs-variable-whats-the-difference
DJTripleThreat