Differences between SET and SELECT assignment in SQL _ MySQL
Source: Internet
Author: User
Based on the difference between the SET and SELECT values in SQL statements, bitsCN.com has many SQL statements recently written in the latest project. it is often used to assign values to variables, and I use SET and SELECT statements to achieve results.
What is the difference between the two? When and which one?
After online queries and personal exercises, the two are summarized as follows:
Suppose there are set variables:
1. SELECT can assign values to multiple variables at the same time in a statement, while SET can assign values to only one variable at a time, as shown below:
SELECT @ VAR1 = 'y', @ VAR2 = 'n'
-- To achieve the same effect, SET needs:
SET @ VAR1 = 'y'
SET @ VAR2 = 'n'
/*
Speaking of this, SQL built-in variables: @ ERROR and @ ROWCOUNT must be captured in an SQL statement. If you use set to obtain them in two sentences, the result is incomplete. in this case, select should be used to obtain the value.
*/
2. when the expression returns multiple values, an error occurs when you use SET, and SELECT takes the last value as follows:
---- Assume that the Permission table has multiple IsRight records.
SELECT @ VAR1 = IsRight FROM Permission -- takes the last value
SET @ VAR1 = IsRight FROM Permission -- an error is returned.
3. when the expression has no return value, use SET to SET the variable value to NULL and use SELECT to maintain the variable value, as shown below:
---- Assume that the Permission record is null.
SET @ VAR1 = 'initiator'
SELECT @ VAR1 = IsRight FROM Permission -- at this time @ VAR1 is the 'initiator'
SET @ VAR1 = (SELECT IsRight FROM Permission) -- @ VAR1 is NULL
4. if the scalar quantum query has no return value, SET and SELECT are both SET to NULL, as shown below:
---- Assume that the Permission record is null.
SET @ VAR1 = 'initiator'
SELECT @ VAR1 = (SELECT IsRight FROM Permission) -- @ VAR1 is NULL
SET @ VAR1 = (SELECT IsRight FROM Permission) -- @ VAR1 is NULL
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service