Basic usage of IF case conditional statement in MySQL

Source: Internet
Author: User
Tags numeric value

An If expression

IF (EXPR1,EXPR2,EXPR3)

If Expr1 is true (expr1 <> 0 and Expr1 <> NULL), then the return value of if () is expr2; Otherwise, the return value is EXPR3. The return value of IF () is a numeric value or a string value, depending on the context in which it is located

Examples are as follows:

The code is as follows Copy Code

SELECT IF (score>=60, ' Pass ', ' fail ') from score;

Mysql> SELECT IF (1>2,2,3);
-> 3
Mysql> SELECT IF (1<2, ' yes ', ' no ');
-> ' yes '
Mysql> SELECT IF (STRCMP (' Test ', ' test1 '), ' no ', ' yes ');
-> ' No '

If the result is greater than 2, then the case will be used, the syntax is:

Case field name when value 1 THEN result 1 when value 2 THEN result 2 Else other result end
Examples are as follows:

The code is as follows Copy Code

SELECT Case Value
When 1 THEN ' A '
When 2 THEN ' B '
When 3 THEN ' C '
ELSE ' D '
End as text
From Test;

If case stored procedure

The code is as follows Copy Code

Wrong wording

CREATE PROCEDURE test (in a int)
If a > 1 Then
Select 1;
ElseIf A>2 Then
Select 2;
Else

End If;

To determine the wording of a

CREATE PROCEDURE test (in a int)
If a > 1 Then
Select 1;
ElseIf A>2 Then
Select 2;
Else
--Doing nothing--
Set @tmp = 1;
End If;

Example

  code is as follows copy code

DROP PROCEDURE IF EXISTS text;

Create PROCEDURE text (
out RTN int 
)
begin

 declare loginID int default 0;

 set rtn=1; 

 if loginID = 3
 then
  set rtn=2;
 elseif loginid = 0
 then
&NBSP;&N Bsp;set rtn=3;
 else
  set rtn=4;
 end IF;

End

Related Article

Contact Us

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.