Home >Database >Mysql Tutorial >How Do I Declare and Use Variables in MySQL?

How Do I Declare and Use Variables in MySQL?

Linda Hamilton
Linda HamiltonOriginal
2025-01-22 03:06:10215browse

How Do I Declare and Use Variables in MySQL?

Detailed explanation of MySQL variables

MySQL supports multiple types of variables for storing and manipulating data:

User-defined variables

  • Starts with "@" symbol.
  • Use SET or SELECT statements for assignment.
  • Only valid in the current user session.
  • Example: SET @变量名 = 值;

Local variables

  • does not start with any symbol.
  • Must be declared using the DECLARE statement before it can be used.
  • Only valid within the scope of a stored procedure or function.
  • Example: DECLARE 变量名 数据类型 DEFAULT 值;

Server system variables

  • Start with "@@" symbol.
  • Set server-wide configuration options.
  • Can be modified dynamically using SET GLOBAL or SET SESSION.
  • Example: SHOW VARIABLES LIKE '%变量名%'; View current settings.

Code Example

The following code demonstrates the use of user-defined variables:

<code class="language-sql">SET @起始值 = 1, @结束值 = 10;

SELECT * FROM places WHERE place BETWEEN @起始值 AND @结束值;</code>

User-defined variables @起始值 and @结束值 are used here. The SET statement initializes these two variables. The BETWEEN operator filters results where the place column value is within the specified range.

The above is the detailed content of How Do I Declare and Use Variables in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn