SQL Server database Logical control statements

Source: Internet
Author: User
Tags case statement

the If-else statement in//sql
IF (condition)
BEGIN
Statement 1
Statement 2
... ...
END
ELSE
BEGIN
Statement 1
Statement 2
... ...
END


Example:
IF (@score > 85)
PRINT ' Exam level: ' + ' excellent '
ELSE IF (@score > 70)
PRINT ' Exam level: ' + ' good '
ELSE IF (@score > 60)
PRINT ' Exam level: ' + ' Medium '
ELSE
PRINT ' Exam level: ' + ' difference '

The while statement in SQL
while (condition)
BEGIN
Statement 1
Statement 2
......
Break
END


Example:
DECLARE @n INT--Failed number
while (1 = 1)-Conditions are always set
BEGIN
SELECT @n=count (*) from Result WHERE [email protected] and [email protected] and Studentresult < 60--number of failed statistics
IF (@n > 0)--plus 2 points per person
UPDATE result SET studentresult=studentresult+2 from Result WHERE [email protected] and [email protected] and Studentresul T < 95
ELSE
Break--Exit loop
END


Case-end Multi-Branch statements
Case
When condition 1 then result 1
When condition 2 then result 2
......
else other results
END
Note: Else indicates that all when conditions in a case are not true when the result is returned
If else is omitted and when condition is false, the case statement returns null

Example:
SELECT study number =studentno, score =case
When Studentresult < ' E '
When Studentresult between, and then ' D '
When studentresult between and "C"
When Studentresult between and the then ' B '
ELSE ' A '
END
From Result
INNER JOIN Subject on Result.subjectno=subject.subjectno

SQL Server database Logical control statements

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.