SqlServer stored procedure in detail

I saw the SQL server stored procedures summarized by others and thought it was well written, so I took it and hoped it would be helpful to everyone.

1. Create a basic syntax template for stored procedures:

if (exists (select * from sys.objects where name = 'pro_name'))
    drop proc pro_name
go
create proc pro_name
    @param_name param_type [=default_value]
as
begin    
    sql语句
end

ps:[] indicates optional content. sys.objects stores the information in this database, not only the table name, but also the stored procedure name, view name, trigger, and so on.

E.g:

 1 if (exists (select * from sys.objects where name = 'USP_GetAllUser'))
 2     drop proc USP_GetAllUser
 3 go
 4 create proc USP_GetAllUser
 5 @UserId int =1
 6 as 
 7 set nocount on;
 8 begin
 9     select * from UserInfo where Id=@UserId
10 end

 

ps: The SQL Server utility interprets GO as a signal that the current Transact-SQL batch statement should be sent to SQL Server. The current batch statement is all the statements entered since the last GO command. If it is the first GO command, it is all the statements from the beginning of the special session or script to this GO command.

2. Calling method:

exec dbo.USP_GetAllUser 2;

 

ps: Generally, when executing a stored procedure, it is best to add an architecture name, such as dbo.USP_GetAllUser. This can reduce unnecessary system overhead and improve performance. Because if there is no schema name in front of the stored procedure name, SQL SERVER will first start searching from the current database sys schema (system schema), if not found, it will search for other schemas, and finally in the dbo schema (system administrator schema) Look inside.

 

3. View the stored procedures that exist in this database

Expand the database, programmability, and stored procedures in turn to see the stored procedures that have been created.

4. Modify the stored procedure

alter proc proc_name 
as 
  sql statement

5. The use of output parameters in the stored procedure

 

 1 if (exists(select * from  sys.objects where name='GetUser'))
 2     drop proc GetUser
 3 go 
 4 create proc GetUser
 5     @id int output,
 6     @name varchar(20) out
 7 as 
 8 begin 
 9     select @id=Id,@name=Name from UserInfo where Id=@id
10 end
11 
12 go 
13 declare 
14 @name varchar(20),
15 @id int;
16 set @id=3;
17 exec dbo.GetUser @id,@name out;
18 select @id,@name;
19 print Cast(@id as varchar(10))+'-'+@name;

 

ps: The parameter output is the parameter can be output

6. Stored procedure for paging to get data

 

 1 if (exists(select * from  sys.objects where name='GetUserByPage'))
 2     drop proc GetUserByPage
 3 go 
 4 create proc GetUserByPage
 5     @pageIndex int,
 6     @pageSize int
 7 as 
 8 declare 
 9 @startIndex int,
10 @endIndex int;
11 set @startIndex =  (@pageIndex-1)*@pageSize+1;
12 set @endIndex = @startIndex + @pageSize -1 ;
13 begin 
14     select Id,Name from 
15     (
16         select *,row_number()over (order by Id)as number from UserInfo  
17     )t where t.number>=@startIndex and t.number<=@endIndex
18 end
19 
20 go 
21 exec dbo.GetUserByPage 2,4;

 

7. The creation of transactions in the stored procedure

 

if (exists(select * from  sys.objects where name='JayJayToTest'))
    drop proc JayJayToTest
go 
create proc JayJayToTest
    @GiveMoney int,
    @UserName nvarchar(20)
as 
beginset nocount on;
    begin tran;
    begin try
        update BankTest set Money = Money-@GiveMoney where Name=@UserName;
        update BankTest set Money = Money+@GiveMoney where Name='test';
        commit;
    end try    
    begin catch        
        rollback tran;
        print ('发生异常,事务进行回滚');
    end catch    
end
go
exec JayJayToTest 10,'jayjay

8. Understand the execution plan of the stored procedure

SELECT * FROM sys.[syscacheobjects] view the current cached execution plan

If the parsing phase is successfully passed when the stored procedure is executed, the Microsoft SQL Server query optimizer will analyze the Transact-SQL statement in the stored procedure and create an execution plan. The execution plan describes the fastest way to execute a stored procedure, based on information including:

  1. The amount of data in the table.

  2. The existence and characteristics of the index of the table, and the distribution of the data in the index column.

  3. The comparison operator and comparison value used in the WHERE clause condition.

  4. Whether there is a connection and the keywords of UNION, GROUP BY and ORDER BY.

After analyzing these factors in the stored procedure, the query optimizer puts the execution plan in memory. The process of analyzing stored procedures and creating execution plans is called compilation. The optimized execution plan in memory will be used to execute the query. The execution plan will stay in memory until the restart of SQL Server or other objects require storage space. If the stored procedure is subsequently executed and the existing execution plan remains in memory, SQL Server will reuse the existing execution plan. If the execution plan is no longer in memory, a new execution plan is created.

Recompile the execution plan (create proc JayJayToTest with recompile)

Specifying the WITH RECOMPILE option in its definition when creating a stored procedure indicates that SQL Server will not cache the stored procedure plan; the stored procedure will be recompiled each time it is executed. When the parameter values ​​of the stored procedure vary greatly between executions, and a different execution plan needs to be created each time, you can use the WITH RECOMPILE option. This option is not commonly used because it must be recompiled each time the stored procedure is executed, which will slow down the execution of the stored procedure.

Due to the new state of the database, certain changes within the database may cause the execution plan to be inefficient or no longer valid. SQL Server detects these changes that invalidate the execution plan and marks the plan as invalid. After that, the new plan must be recompiled for the next connection to execute the query. Circumstances that made the plan invalid include:

  1. Make any structural changes to the table or view referenced by the query (ALTER TABLE and ALTER VIEW).
  2. Explicitly generate or automatically generate new distribution content statistics through statements (such as UPDATE STATISTICS).
  3. Remove the index used by the execution plan.
  4. Explicitly call sp_recompile.
  5. A large number of changes to the keys (modifications produced by other users using INSERT or DELETE statements on the tables referenced by the query).
  6. For tables with triggers, the number of rows in the inserted or deleted table has increased significantly.

Guess you like

Origin blog.csdn.net/h610443955/article/details/83185528