首頁 > 資料庫 > mysql教程 > MySQL – Introduction to User Defined Variables_MySQL

MySQL – Introduction to User Defined Variables_MySQL

WBOY
發布: 2016-06-01 13:12:29
原創
1046 人瀏覽過

MySQL supports user defined variables to have some data that can be used later part of your query. You can save a value to a variable using a SELECT statement and later you can access its value.

Unlike other RDBMSs, you do not need to declare the data type for a variable. The data type is automatically assumed when you assign a value. A value can be assigned to a variable using a SET command as shown below

SET @server_type:='MySQL';<br>

When you above command is executed, the value, MySQL is assigned to the variable called @server_type. Now you can use this variable in the later part of the code. Suppose if you want to display the value, you can use SELECT statement.

SELECT @server_type;

The result is MySQL. Once the value is assigned it remains for the entire session until changed by the later statements. So unlike SQL Server, you do not need to have this as part the execution code every time. (Because in SQL Server, the variables are execution scoped and dropped after the execution).

You can give column name as below

SELECT @server_type AS server_type;

You can also SELECT statement to DECLARE and SELECT the values for a variable.

SELECT @message:='Welcome to MySQL' AS MESSAGE;

The result is

Message --------Welcome to MySQL
登入後複製

You can make use of variables to effectively apply many logics. One of the useful method is to generate the row number as shown in this postMySQL – Generating Row Number for Each Row using Variable.

Reference: Pinal Dave (http://blog.sqlauthority.com)

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板