MySQL 中的分隔符

时间:2023-04-02
本文介绍了MySQL 中的分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我经常看到人们使用分隔符.我试图自己找出什么是分隔符以及它们的目的是什么.经过 20 分钟的谷歌搜索,我找不到让我满意的答案.所以,我现在的问题是:什么是分隔符,我应该在什么时候使用它们?

I often see people are using Delimiters. I tried myself to find out what are delimiters and what is their purpose. After 20 minutes of googling, I was not able to find an answer which satisfies me. So, my question is now: What are delimiters and when should I use them?

推荐答案

除默认 ; 之外的定界符通常用于定义函数、存储过程和触发器,其中必须定义多个语句.您定义了一个不同的分隔符,如 $$,它用于定义整个过程的结束,但在其中,各个语句都以 ; 终止.这样,当代码在mysql客户端中运行时,客户端可以知道整个过程在哪里结束并作为一个单元执行,而不是执行内部的单个语句.

Delimiters other than the default ; are typically used when defining functions, stored procedures, and triggers wherein you must define multiple statements. You define a different delimiter like $$ which is used to define the end of the entire procedure, but inside it, individual statements are each terminated by ;. That way, when the code is run in the mysql client, the client can tell where the entire procedure ends and execute it as a unit rather than executing the individual statements inside.

请注意,DELIMITER 关键字只是命令行 mysql 客户端(和一些其他客户端)的函数,而不是常规 MySQL 语言功能.如果您尝试通过编程语言 API 将其传递给 MySQL,它将无法工作.其他一些客户端(如 PHPMyAdmin)有其他方法来指定非默认分隔符.

Note that the DELIMITER keyword is a function of the command line mysql client (and some other clients) only and not a regular MySQL language feature. It won't work if you tried to pass it through a programming language API to MySQL. Some other clients like PHPMyAdmin have other methods to specify a non-default delimiter.

DELIMITER $$
/* This is a complete statement, not part of the procedure, so use the custom delimiter $$ */
DROP PROCEDURE my_procedure$$

/* Now start the procedure code */
CREATE PROCEDURE my_procedure ()
BEGIN    
  /* Inside the procedure, individual statements terminate with ; */
  CREATE TABLE tablea (
     col1 INT,
     col2 INT
  );

  INSERT INTO tablea
    SELECT * FROM table1;

  CREATE TABLE tableb (
     col1 INT,
     col2 INT
  );
  INSERT INTO tableb
    SELECT * FROM table2;
  
/* whole procedure ends with the custom delimiter */
END$$

/* Finally, reset the delimiter to the default ; */
DELIMITER ;

尝试在不支持它的客户端上使用 DELIMITER 会导致它被发送到服务器,服务器会报告语法错误.例如,使用 PHP 和 MySQLi:

Attempting to use DELIMITER with a client that doesn't support it will cause it to be sent to the server, which will report a syntax error. For example, using PHP and MySQLi:

$mysqli = new mysqli('localhost', 'user', 'pass', 'test');
$result = $mysqli->query('DELIMITER $$');
echo $mysqli->error;

错误:

您的 SQL 语法有错误;检查对应的手册到您的 MySQL 服务器版本,以便在第 1 行的DELIMITER $$"附近使用正确的语法

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 'DELIMITER $$' at line 1

这篇关于MySQL 中的分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何优化 MySQL 的 ORDER BY RAND() 函数? 下一篇:utf8_general_ci 和 utf8_unicode_ci 有什么区别?

相关文章