Laravel迁移原始sql错误

时间:2014-12-11 09:35:11

标签: mysql sql laravel levenshtein-distance

我想在Laravel中使用Levenshtein距离进行搜索。我找到了SQL函数(保存为app/database/migrations/levenshtain.sql):

    DELIMITER //
    CREATE FUNCTION `LEVENSHTEIN`(s1 VARCHAR(255) CHARACTER SET utf8, s2 VARCHAR(255) CHARACTER SET utf8) RETURNS int(11)
        DETERMINISTIC
    BEGIN
        DECLARE s1_len, s2_len, i, j, c, c_temp, cost INT;
        DECLARE s1_char CHAR CHARACTER SET utf8;
        -- max strlen=255 for this function
        DECLARE cv0, cv1 VARBINARY(256);

        SET s1_len = CHAR_LENGTH(s1),
            s2_len = CHAR_LENGTH(s2),
            cv1 = 0x00,
            j = 1,
            i = 1,
            c = 0;

        IF (s1 = s2) THEN
          RETURN (0);
        ELSEIF (s1_len = 0) THEN
          RETURN (s2_len);
        ELSEIF (s2_len = 0) THEN
          RETURN (s1_len);
        END IF;

        WHILE (j  c_temp) THEN
              SET c = c_temp;
            END IF;

            SET c_temp = ORD(SUBSTRING(cv1, j+1, 1)) + 1;
            IF (c > c_temp) THEN
              SET c = c_temp;
            END IF;

            SET cv0 = CONCAT(cv0, CHAR(c)),
                j = j + 1;
          END WHILE;

          SET cv1 = cv0,
              i = i + 1;
        END WHILE;

        RETURN (c);
      END//
    DELIMITER ;

在迁移中:


    public function up () {
        DB::statement(file_get_contents(__DIR__.'/levenshtein.sql'));
    }
    public function down () {
        DB::statement('DROP FUNCTION `LEVENSHTEIN`;');
    }

我尝试了DB::statementDB::unpreparedDB::raw,但是Laravel迁移会抛出错误:


    [Illuminate\Database\QueryException]
      SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in yo
      ur SQL syntax; check the manual that corresponds to your MySQL server version f
      or the right syntax to use near 'DELIMITER //
      CREATE FUNCTION `LEVENSHTEIN`(s1 VARCHAR(255) CHARACTER SET utf8, ' at line 1

当我用HeidiSQL执行它时它会起作用,问题是什么?

1 个答案:

答案 0 :(得分:0)

我在Creating MYSQL Procedure in Laravel 4 Migrations找到了@peterm回答的解决方案。

DELIMITER //中的问题不是有效的sql语句。它只是一个MySql客户端命令。