Home  >  Article  >  Database  >  How to assign query results to variables in mysql

How to assign query results to variables in mysql

青灯夜游
青灯夜游Original
2022-01-24 18:14:2116434browse

Mysql method of assigning query results to variables: 1. Use the "DECLARE variable name type [DEFAULT default value];" statement to create a variable; 2. Use "SELECT field name INTO variable name FROM table name WEHRE query "Condition;" statement assigns the query results to variables.

How to assign query results to variables in mysql

The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.

Mysql method of assigning query results to variables

1. Create variables

MySQL You can use the DECLARE keyword to define variables. The basic syntax is as follows:

DECLARE 变量名 类型 [DEFAULT 默认值]

If the DEFAULT clause is omitted, the default value is NULL.

Example: Define the variable my_sql, the data type is INT type

DECLARE my_sql INT;

2. Assign the query results to the variable

You need to use SELECT ..INTO statement, its basic syntax is as follows:

SELECT col_name [...] INTO var_name[,...]
FROM table_name WEHRE condition

Among them:

  • col_name parameter represents the query field name;

  • ## The
  • #var_name parameter is the name of the variable; the

  • table_name parameter refers to the name of the table; the

  • condition parameter refers to the query condition.

Note: When assigning query results to variables, the query statement can only return a single row.

Example: Query the record with id 2 from the tb_student table, and assign the id value of the record to the variable my_sql. The SQL statement is as follows:

SELECT id INTO my_sql FROM tb_student WEHRE id=2;

[Related recommendations:

mysql video tutorial]

The above is the detailed content of How to assign query results to 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