0

我是 MYSQL 编程的新手。我想使用 MYSQL 循环脚本将一个非常大的表选择到几个 csv 文件中。我的脚本如下:

BEGIN
        SET @t_lines=0;
        SET @t_count=0;
        SET @t_filepath='/home/ab/path/table_name_02212013_';
        WHILE t_lines<=5000000
        SET @t_filename=CONCAT(@t_filepath,CAST(@t_count as CHAR));
        select * into outfile @t_filename fields terminated by ',' optionally enclosed by '"' lines terminated by '\n' from table_name limit @t_lines,@t_lines+300000;
        SET @t_lines= @t_lines+300000;
        SET @t_count= @t_count+1;
        END WHILE;
        COMMIT;
END

我在一行中遇到语法错误:

SET @t_filename=CONCAT(@t_filepath,CAST(@t_count as CHAR));

WHILE ... DO 导致的语法错误。感谢您的快速回复。在这里,“限制”之后,“@t_lines,@t_lines+300000”处仍然存在语法错误。我想通了,似乎“限制”不允许“@t_lines+300000”给出行范围。可以通过提供一个新变量来修复它:

   BEGIN
            DECLARE t_lines INT DEFAULT 0;
            DECLARE t_count INT DEFAULT 0;
            DECLARE t_endlines INT DEFAULT 300000;
            DECLARE t_linerange INT DEFAULT 300000;
            SET @t_filepath='/home/ab/path/table_name_02212013_';
            WHILE t_lines<=5000000 DO
            SET @t_filename=CONCAT(@t_filepath,CAST(@t_count as CHAR));
            select * into outfile '@t_filename' fields terminated by ',' optionally enclosed by '"' lines terminated by '\n' from table_name limit t_lines,t_endlines;
            SET t_lines= t_lines+t_linerange;
            SET t_endlines= t_endlines+t_linerange
            SET t_count= t_count+1;
            END WHILE;
            COMMIT;
    END

非常感谢

4

3 回答 3

1

MySQL 中循环语法WHILE需要一个DO;

WHILE t_lines<=5000000 DO
...
END WHILE;
于 2013-02-21T13:58:28.580 回答
1

的文件名参数INTO OUTFILE 必须是文字字符串。您不能使用变量或表达式作为文件名。

的参数LIMIT必须是整数常量。您可以使用参数占位符 ( ?)、存储过程参数或本地过程变量(您声明的那些)。但是您不能使用会话变量(带有@前缀的变量),也不能使用表达式

您必须将查询创建为 SQL 字符串,并将值插入到字符串中。
然后将该 SQL 字符串与PREPAREandEXECUTE一起使用。

于 2013-02-21T16:13:03.400 回答
0

尝试 :

convert(columnName, char)

-->

BEGIN
        SET @t_lines=0;
        SET @t_count=0;
        SET @t_filepath='/home/ab/path/table_name_02212013_';
        WHILE t_lines<=5000000
        SET @t_filename=CONCAT(@t_filepath,convert(@t_count, CHAR));
        select * into outfile @t_filename fields terminated by ',' optionally enclosed by '"' lines terminated by '\n' from table_name limit @t_lines,@t_lines+300000;
        SET @t_lines= @t_lines+300000;
        SET @t_count= @t_count+1;
        END WHILE;
        COMMIT;
END
于 2013-02-21T13:59:17.523 回答