SQL stored procedure BASICS (Process Control)

Source: Internet
Author: User

Here we will talk about the process control of the stored procedure. if else, case, while, there is no for loop here. These are not as good as c, c ++, c # and other languages.

First, let's look at the use of if else
Copy codeThe Code is as follows:
If condition
Begin
SQL statement
End
Else begin
SQL statement
End

Let's look at a simple example.
Copy codeThe Code is as follows:
Declare @ id int -- declare Variables
Set @ id = 5 -- set the kitchen Initial Value
If (@ id = 1)
Begin
Print 'right'
End
Else if (@ id = 0)
Begin
Print 'error'
End
Else
Begin
Print 'default'
End

As a result, I think everyone should know it and I will not write it out. The begin and end here can also be left empty, but it is recommended to write it. This is like the {} of c ++ code, which indicates a piece, the written layers are clearer.

Of course, if Nesting is also possible.

Ii. Use of While


Let's calculate the sum from 1 to 100.

Copy codeThe Code is as follows:
Declare @ I int, @ sum int
Set @ I = 0
Set @ sum = 0
While @ I <= 100 -- start Loop
Begin
Set @ I = @ I + 1 -- Auto increment 1
Set @ sum = @ sum + @ I
End
Print @ sum
Result
-----------

Iii. Use of multiple Case options

Copy codeThe Code is as follows:
Declare @ iret int, @ var varchar (10)
Set @ var = 'A'
Select @ iret =
Case when @ var = 'A' then 0
When @ var = 'B' then 1
When @ var = 'C' then 2
When @ var = 'D' then 3
Else-1
Print @ iret

Result
-------

The above basic process control can basically meet our daily development needs, so much has been thought of for the time being. When we think of other situations, we will add them as appropriate.

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.