使用C#在MySQL中创建存储过程

时间:2013-08-08 23:41:11

标签: c# mysql stored-procedures

我正在尝试使用以下代码以编程方式创建新的存储过程:

using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();

                using (MySqlTransaction trans = conn.BeginTransaction())
                {
                    using (MySqlCommand command = conn.CreateCommand())
                    {
                        command.CommandText = query;

                        command.ExecuteNonQuery();
                    }

                    trans.Commit();
                }
            }

以下文本作为从Mysql workbench复制的create语句:

static string query = @"
delimiter $$

CREATE PROCEDURE `GetParentIds`(IN `tempTableName` VARCHAR(255), IN `id` int)
BEGIN
DECLARE parId INT;
DECLARE curId INT;

  DROP TEMPORARY TABLE IF EXISTS tempTableName;

  CREATE TEMPORARY TABLE tempTableName (
node_id INT NOT NULL PRIMARY KEY
   );

 set curId := id;
 get_parents_loop: LOOP
     set parId := null;

     set parId = (select ParentID from {TableName} where ID = curId);

    IF parId is NULL THEN
       LEAVE get_parents_loop;
    END IF;

    INSERT INTO tempTableName(node_id) Values (parId);
    set curId := parId;

END LOOP get_parents_loop;
  SELECT *
     FROM tempTableName;
END$$";

此过程传递一个具有parentID的对象的ID,它获取给定对象的所有父项的所有parentID并返回它们。当我尝试运行它并且收到以下消息时出现问题: “您的SQL语法有错误;请查看与您的MySQL服务器版本对应的手册,以便在'delimiter $$'附近使用正确的语法

CREATE PROCEDURE GetParentIds(IN tempTableName VARCHAR(255),'第1行'

欢迎任何和所有想法!

*编辑** 感谢下面的所有答案,这就是最终的工作:

CREATE PROCEDURE GetParentIds(IN tempTableName VARCHAR(255), IN id int)
BEGIN
DECLARE parId INT;
DECLARE curId INT;

DROP TEMPORARY TABLE IF EXISTS tempTableName;

 CREATE TEMPORARY TABLE tempTableName (node_id INT NOT NULL PRIMARY KEY  );

set curId := id;
get_parents_loop: LOOP
    set parId := null;

    set parId = (select ParentID from TDOs where TDOID = curId);

    IF parId is NULL THEN
       LEAVE get_parents_loop;
    END IF;

    INSERT INTO tempTableName(node_id) Values (parId);
    set curId := parId;

END LOOP get_parents_loop;
  SELECT *
    FROM tempTableName;
END;

2 个答案:

答案 0 :(得分:5)

在开始时移除DELIMITER $$,在最后$$

之后移除END

DELIMITER mysql客户端命令,使您可以在定义存储例程时临时更改其语句终止符。

如果要在不使用分号作为语句终止符的编程接口中定义存储例程,则存储例程定义中的分号不会出现任何特殊问题。

答案 1 :(得分:-1)

静态字符串查询= @"

CREATE PROCEDURE ZGetParentIds(IN tempTableName VARCHAR(255),IN id int) 开始 DECLARE parId INT; DECLARE curId INT;

DROP TEMPORARY TABLE IF EXISTS tempTableName;

CREATE TEMPORARY TABLE tempTableName(node_id INT NOT NULL PRIMARY KEY);

  set curId := id;
  get_parents_loop: LOOP
  set parId := null;

set parId = (select ParentID from TDOs where TDOID = curId);

IF parId is NULL THEN
   LEAVE get_parents_loop;
END IF;

INSERT INTO tempTableName(node_id) Values (parId);
set curId := parId;

END LOOP get_parents_loop;   选择 *     FROM tempTableName; END&#34 ;;