About the basics of getting started with SQL stored procedures (Process Control) _mssql

Source: Internet
Author: User

Here we talk about the process control of the stored procedure, if else,case, while, there is no for loop, these and c,c++,c# languages are poor.

First, let's see if else uses

Copy Code code as follows:

If condition
Begin
SQL statement
End
ELSE begin
SQL statement
End

Look at a simple example
Copy Code code as follows:

DECLARE @id INT--Declaring a variable
Set @id = 5--Setting Kitchen initial value
if (@id =1)
Begin
print ' Right '
End
else if (@id =0)
Begin
print ' ERROR '
End
Else
Begin
print ' Default '
End

The result I think everybody should know, don't write out, here begin, end also can not write, but suggest write, this like C + + code {}, say a piece, write to the level clearer.

Of course, if nesting is also possible.

Two, while the use of


We're going to calculate the sum of 1 to 100.

Copy Code code as follows:

Declare @i int, @sum int
Set @i=0
Set @sum =0
While @i<=100--Start loop
Begin
Set @i=@i+1--self-adding one
Set @sum = @sum +@i
End
Print @sum
Results
-----------

Three, case multiple choice of use

Copy Code code 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

Results
-------

The above basic flow control, basically can meet our daily development needs, temporarily think of so much, which day think of other circumstances, will be appropriate to supplement.

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.