简体   繁体   English

SQL if 语句语法错误

[英]SQL if statement syntax error

I've been trying to write this simple mysql statement to check if a table exists:我一直在尝试编写这个简单的 mysql 语句来检查表是否存在:

IF object_id('carpool'.'users', 'U') is not null THEN
    PRINT 'Present!'
ELSE
    PRINT 'Not accounted for'
END IF

'carpool' is my schema and 'users' is a table My sql version is 5.1.52-community I keep getting this error: 'carpool' 是我的架构,'users' 是一个表我的 sql 版本是 5.1.52-community 我不断收到这个错误:

Error Code: 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 'IF' at line 1   0.000 sec

I've tried several syntaxes such as IF BEGIN END ELSE BEGIN END to no avail.我尝试了几种语法,例如 IF BEGIN END ELSE BEGIN END 都无济于事。 any ideas?有任何想法吗?

It looks like you're trying to do a form of T-SQL, which MySQL does not support.看起来您正在尝试执行一种 MySQL 不支持的 T-SQL 形式。

There is no print function, nor object_id.没有打印功能,也没有 object_id。 There is a form of IF function that can be used in a SELECT statement:有一种形式的 IF 函数可以在 SELECT 语句中使用:

SELECT IF(1 = 1, 'present', 'not');

Are you reading MSSQL doco instead of MySQL doco?你在读 MSSQL doco 而不是 MySQL doco 吗? MSSQL supports these functions. MSSQL 支持这些功能。

Depending on what you are after, you might want to use something like this:根据您的要求,您可能想要使用以下内容:

SELECT
  CASE WHEN EXISTS (SELECT NULL
                    FROM information_schema.tables 
                    WHERE table_schema = 'carpool' AND table_name = 'users')
       THEN 'Present'
       ELSE 'Not accounted for' END;

This will check if table users exists in carpool schema.这将检查carpool模式中是否存在表users Please see example here .在此处查看示例。

Every statement must be terminated by semicolon.每条语句都必须以分号结束。

Like this像这样

IF object_id('carpool'.'users', 'U') is not null THEN
   PRINT 'Present!';
ELSE
   PRINT 'Not accounted for';
END IF;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM