1

I'm trying to create a function in my mySQL database using entity framework migrations. The SQL works great when I run it directly in MySQL Workbench but it fails when it runs in the EF migration.

How can I create a function using EF migration?

     Sql(@"
DROP function IF EXISTS `f_JumperName`;

DELIMITER $$
CREATE FUNCTION `f_JumperName` 
(
    JumperID int
)
RETURNS varchar(500)
BEGIN
    DECLARE result VARCHAR(500);

    SELECT j.LastName + ', ' + j.FirstName
    INTO result
    FROM Jumper j
    WHERE j.JumperID = JumperID;

    RETURN x;
END$$

DELIMITER ;
");

Error message: 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 'DELIMITER $$ CREATE FUNCTION f_JumperName (...

1 Answer 1

6

It seems the problem is caused by the DELIMITER sentences.

To work around it you can split your SQL in sentences, so you don't need to redefine the ; delimiter. You get two separate sentences, one for the drop and one for the create function:

public override void Up()
{
    Sql(@"DROP function IF EXISTS `f_JumperName`;");
    Sql(@"CREATE FUNCTION `f_JumperName` 
        (
            JumperID int
        )
        RETURNS varchar(500)
        BEGIN
            DECLARE result VARCHAR(500);
            SELECT j.LastName + ', ' + j.FirstName
            INTO result
            FROM Jumper j
            WHERE j.JumperID = JumperID;

            RETURN x;
        END;");
}

And you replace your previous $$ characters with ; at the end of the second sentence.

This is not fixing the real problem, which is not being able to set the delimiter correctly, but it works. I found some pages about really changing the delimiter through the MySqlScript.Delimiter property provided by the MySQL connector, but I don't know if it is a good practice (or even possible) to use it in a migration file, because you would have to access the real connection to the database somehow. I'm not really sure this can be used here.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much Diana, that worked. It would be nice if the same command that runs in mySQL Workbench worked in EF as well, but I'm happy to have a work around.
I was doubting this answer at first, but actually, it works great :) Works for CREATE PROCEDURE as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.