这个MySQL查询有问题吗?

时间:2010-08-17 21:01:29

标签: sql mysql syntax

我是第一次编写存储过程,但它无法正常工作。麻烦的是我看不出它不工作的原因。

我通过phpmyadmin 2.8.2.4运行它。我的MySQL版本是5.1。以下是查询的第一部分:

create procedure under_user_type (in original_post int, out user_type int, out user_id longtext)
begin
    if exists (
        select *
            from wp_postmeta as pm
            where pm.post_id = original_post
            and pm.meta_key = '_tdomf_original_poster_id'
    ) then
        set user_type = 0;
        select pm.meta_value
            into user_id
            from wp_postmeta as pm
            where pm.post_id = original_post
            and pm.meta_key = '_tdomf_original_poster_id';

    elseif exists ( ...

我收到错误:
#1064 - 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 '' at line 9

第9行对应if exists ( ... ) then部分中的第一个select语句。

更新

如果我使用,我会收到同样的错误:

create procedure under_user_type (in original_post int, out user_type int, out user_id longtext)
begin
    if 1=1 then begin
        set user_type = 0;
        select pm.meta_value
            into user_id
            from wp_postmeta as pm
            where pm.post_id = original_post
            and pm.meta_key = '_tdomf_original_poster_id';
        end;

再次更新:

this MySQL documentation page上运行示例也会让我“检查你的语法附近''”错误。我尝试从查询中删除所有标签,但没有做任何事情。

第三次更新:

我可以运行此查询:

create procedure blah()
begin
end;

但不是这个查询:

create procedure blah2()
begin
   if 1=1 then
   begin
   end;
   end if;
end;

因为我得到同样的错误。

4 个答案:

答案 0 :(得分:1)

以下适用于我:

create procedure blah2()
begin
  declare s int;
  if exists(select 1) then
    set s=1;
  end if;
end;

我认为你的问题(在第一个例子中,在你尝试进行所有实验之前)是你没有声明变量user_type,所以MySQL在它打印出一个(非常通用的)错误遇到一个在第9行上从未见过的变量名。

(至于您的所有其他示例,不应该执行if ... then begin ... end;正确的语法是if ... then ... elseif ... else ... end if

答案 1 :(得分:0)

当遇到第一个分号时,错误在第9行。

如果您要在程序体内使用分号,则需要将DELIMITER设置为除分号以外的其他值。

以下是如何为最简单的示例执行此操作:

DELIMITER $$

create procedure blah2()
begin
   if 1=1 then
   begin
   end;
   end if;
end $$

DELIMITER ;

答案 2 :(得分:0)

问题是PHPMyAdmin每次看到分号时都必须尝试拆分查询。这就是MySQL CLI所做的,这就是为什么在命令行上创建存储过程时需要更改分隔符的原因。但是,我的PHPMyAdmin版本(2.8.2.4)不允许我更改分隔符,所以我最后收到了一堆无用的错误消息。

我在远程服务器上编写了一个带有textarea和提交按钮的脚本,该按钮将textarea的内容传递给mysqli::multi_query。这个函数让mysql处理分隔符,而不是试图将它自己拆分,因此创建过程在这方面起作用。

另一个更简单的方法是使用MySQL Workbench连接到数据库,如果数据库只允许来自localhost的连接,可能通过ssh。

答案 3 :(得分:-1)

我不认为MySQL可以处理“if exists”。 你可以试试

declare testMe integer default (select ID from ... where ...);

if testMe is not NULL then
...
相关问题