Talking about Stored Procedure in Database

First, the difference between stored procedure and function:

  1. Generally speaking, the functions implemented by stored procedures are a bit more complicated, while the functions implemented by functions are more targeted.

  2. For stored procedures, you can return parameters (output), while functions can only return values ​​or table objects.

  3. The stored procedure is generally executed as an independent part, and the function can be called as a part of the query statement. Since the function can return a table object, it can be located after the FROM keyword in the query statement.

Second, the advantages of stored procedures:

  1. Faster execution – stored procedure statements saved in the database are compiled

  2. Allows for modular programming - reuse of similar methods

  3. Improve system security - prevent SQL injection

  4. Reduce network traffic - just transfer the name of the stored procedure

System stored procedures generally start with sp, and user-defined stored procedures generally start with usp

3. Define the syntax of the stored procedure, the content in "[" indicates optional

create proc stored procedure name

  @parameter1 datatype[=default][output],

  @parameter2 datatype[=default][output],

  ...

  as

Fourth, a simple example

  Define the stored procedure:

 

create proc usp_StudentByGenderAge

  @gender nvarchar(10) [='男'],

  @age int [=30]

  as

  select * from MyStudent where FGender=@gender and FAge=@age

 

  Execute the stored procedure:

 

Situation One (call with default parameters):

  exec usp_StudentByGenderAge

  Situation Two (call the parameters specified by yourself):

  exec usp_StudentByGenderAge '女',50

  Or specify the variable name exec usp_StudentByGenderAge @age=50, @gender='female'

 ```
alter proc usp_StudentByGenderAge

  @gender nvarchar(10) [='男'],

  @age int [=30],

  --Adding output indicates that the parameter needs to be assigned and returned in the stored procedure

  @recorderCount int output

  as

  select * from MyStudent where FGender=@gender and FAge=@age

  set @recorderCount=(select count(*) from MyStudent where FGender=@gender and FAge=@age)

 

The purpose of the –output parameter is that the caller needs to pass a variable in, and then complete the assignment for the variable in the stored procedure. After the stored procedure is executed, the corresponding result of the execution is returned to the passed in variable. (Exactly the same as the out principle in C#)

Call (remember the syntax here!) Because there are other parameters in front of the stored procedure, so write @recorderCount. After the stored procedure is executed, it is equivalent to completing the above query work, and at the same time, the number of query results obtained Assigned to the @count variable.

(@count is passed as a parameter to usp_StudentByGenderAge, and when the stored procedure is executed, the number of obtained items is returned to @count)

  declare @count int

  exec usp_StudentByGenderAge @recorderCount=@count output

  print @count
 ```
alter proc usp_StudentByGenderAge

  @gender nvarchar(10) [='男'],

  @age int [=30],

  --Adding output indicates that the parameter needs to be assigned and returned in the stored procedure

  @recorderCount int output

  as

  select * from MyStudent where FGender=@gender and FAge=@age

  set @recorderCount=(select count(*) from MyStudent where FGender
    =@gender and FAge=@age)

 

Fifth, use stored procedures to complete paging

 

1. Stored procedure code

create proc usp_page

  @page int, --- how many records to display on one page

    @number int, --- The number of data pages selected by the user

      as

   begin

   select * from

   --The contents in parentheses are specially arranged serial numbers

   (

     select  ROW_NUMBER() over(order by(Fid))  as number

     from MyStudent

   ) as t

   where t.number>= (@number-1)*@page+1 and t.number<=@number*@page

   end

2. The ADO.NET code corresponding to the paging effect:

First, the difference between stored procedure and function:

  1. Generally speaking, the functions implemented by stored procedures are a bit more complicated, while the functions implemented by functions are more targeted.

  2. For stored procedures, you can return parameters (output), while functions can only return values ​​or table objects.

  3. The stored procedure is generally executed as an independent part, and the function can be called as a part of the query statement. Since the function can return a table object, it can be located after the FROM keyword in the query statement.

Second, the advantages of stored procedures:

  1. Faster execution – stored procedure statements saved in the database are compiled

  2. Allows for modular programming - reuse of similar methods

  3. Improve system security - prevent SQL injection

  4. Reduce network traffic - just transfer the name of the stored procedure

System stored procedures generally start with sp, and user-defined stored procedures generally start with usp

3. Define the syntax of the stored procedure, the content in "[" indicates optional

 

  create proc stored procedure name

  @parameter1 datatype[=default][output],

  @parameter2 datatype[=default][output],

  ...

  as

  SQL statement

Fourth, a simple example

  Define the stored procedure:

  create proc usp_StudentByGenderAge

  @gender nvarchar(10) [='男'],

  @age int [=30]

  as

  select * from MyStudent where FGender=@gender and FAge=@age

  Execute the stored procedure:

 

Situation One (call with default parameters):

  exec usp_StudentByGenderAge

  Situation Two (call the parameters specified by yourself):

  exec usp_StudentByGenderAge '女',50

 

  Or specify the variable name exec usp_StudentByGenderAge @age=50,@gender='female' to modify the stored procedure

alter proc usp_StudentByGenderAge

  @gender nvarchar(10) [='男'],

  @age int [=30],

  --Adding output indicates that the parameter needs to be assigned and returned in the stored procedure

  @recorderCount int output

  as

  select * from MyStudent where FGender=@gender and FAge=@age

  set @recorderCount=(select count(*) from MyStudent where FGender=@gender and FAge=@age)

The purpose of the –output parameter is that the caller needs to pass a variable in, and then complete the assignment for the variable in the stored procedure. After the stored procedure is executed, the corresponding result of the execution is returned to the passed in variable. (Exactly the same as the out principle in C#)

Call (remember the syntax here!) Because there are other parameters in front of the stored procedure, so write @recorderCount. After the stored procedure is executed, it is equivalent to completing the above query work, and at the same time, the number of query results obtained Assigned to the @count variable.

(@count is passed as a parameter to usp_StudentByGenderAge, and when the stored procedure is executed, the number of obtained items is returned to @count)

  declare @count int

  exec usp_StudentByGenderAge @recorderCount=@count output

  print @count

Fifth, use stored procedures to complete paging

1. Stored procedure code

create proc usp_page

  @page int, --- how many records to display on one page

    @number int, --- The number of data pages selected by the user

      as

   begin

   select * from

   --The contents in parentheses are specially arranged serial numbers

   (

     select  ROW_NUMBER() over(order by(Fid))  as number

     from MyStudent

   ) as t

   where t.number>= (@number-1)*@page+1 and t.number<=@number*@page

   end

 

2. The ADO.NET code corresponding to the paging effect:

private void button1_Click(object sender, EventArgs e)
  {
  string connStr = @"server=.\sqlexpress;database=MyDB;integrated security=true";
  using (SqlConnection conn = new SqlConnection(connStr))
  {
    //open database connection
    conn.Open();
    //Use the stored procedure name as the object processed by Command
    string usp = "usp_page";
    using (SqlCommand cmd = new SqlCommand(usp, conn))
    {
      // execute the stored procedure statement
      cmd.CommandType = CommandType.StoredProcedure;
        //textBox1.Text refers to how many records are displayed
      cmd.Parameters.AddWithValue("@page", textBox1.Text.Trim());
      //textBox.Text refers to the page selected by the user
      cmd.Parameters.AddWithValue("@number", textBox2.Text.Trim());
      //Use list as data source to implement
      List<Person> p = new List<Person>();
      using (SqlDataReader reader = cmd.ExecuteReader())
      {
        if (reader.HasRows)
        {
          while (reader.Read())
          {
            Person p1 = new Person();
            p1.FName = reader.GetString(1);
            p1.FAge = reader.GetInt32(2);
            p1.FGender = reader.GetString(3);
            p1.FMath = reader.GetInt32(4);
            p1.FEnglish = reader.GetInt32(5);
            p.Add(p1);
          }
        }
      }
      dataGridView1.DataSource = p;
    }
  }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326938064&siteId=291194637