当前位置:网站首页>Stored procedures in sqlserver

Stored procedures in sqlserver

2022-06-24 18:39:00 MousseIn

  • Stored in advance sql Program ( Database operation statement , Variable , Logic control statements, etc )
  • Save in SQL Server in
  • By name and parameters , Return result .

Advantages of stored procedures :

  • Fast execution
  • Allow modular programming
  • Improve system security
  • Reduce network traffic

System stored procedure

  • The name of the system stored procedure is generally “sp_” start
  • from SQLServer establish 、 Management and use
  • Store in Resource In the database

sp_databases List all the databases on the server
sp_tables Returns the list of objects that can be queried in the current environment
sp_helptext Open another unencrypted stored procedure to view
Examples are as follows

execute sp_databases
exec sp_helptext sp_databases

Extending stored procedures

  • Extended stored procedures are usually named with “xp_” start
  • Using the editing language ( Such as C#) Created external stored procedures
  • With DLL Forms exist alone

xp_cmdshell

  • It can be executed DOS Some operations under the command
  • You can return any output as a line

It is written as follows :

EXEC xp_cmdshell DOS command [NO_OUTPUT]

Examples are as follows :

USE master
GO
/*--- if xp_cmdShell Shut down as part of the server security configuration , Please use the following statement to enable ---*/
Exec sp_configure 'show advanced options ' , 1 -- Display advanced configuration information 
GO
RECONFIGURE -- Reconfiguration 
GO
exec sp_configure 'xp_cmdShell',1-- open xp_configure Options 
GO
REconfigure -- Reconfiguration 
/*--- Create database bankDB, Request to be kept in D:\bank---*/
Exec xp_cmdshell 'mkdir D:\bank', NO_OUTPUT -- Create folder D:\bank
-- Create database bankDB

User defined stored procedures

Parameterless stored procedure

Nonparametric stored procedure definition

CREATE PROC[ EDURE ] Stored procedure name
AS
SQL sentence
GO

Using the syntax of stored procedures :
EXECUTE The process of
EXEC The process of

If the statement executing the stored procedure is the first statement in a batch statement , You may not specify
EXECUTE keyword .

Examples are as follows :

 use MySchool
go
    create proc stuResult
    as
    
    ---- Find this Java OOP  The average score of the test and the information of the people who failed 


    --- Define variables to save the last exam time 

declare @maxDate datetime 




select @maxDate = MAX(ExamDate) from Result
  where SubjectId =(select SubjectId from Subject 
                    where SubjectName = 'Java OOP')
 
 
--- Calculate the average score 
select AVG(StudentResult) from Result
	where ExamDate = @maxDate
	and SubjectId = (select SubjectId from Subject 
                    where SubjectName = 'Java OOP') 
-- Check the list of students who failed the exam 
select * from Student
		where StudentNo =(
	select StudentNo from Result
	where SubjectId =  (select SubjectId from Subject 
                    where SubjectName = 'Java OOP') 
    and ExamDate = @maxDate  
    and StudentResult < 80
    ) 
    go                                 

Calling a parameterless stored procedure

Exec stuResult
    

Stored procedures with parameters

Create stored procedure syntax with parameters

CREAT PROC[EDURE] Stored procedure name
@ Parameters 1,@ Parameters 2,…,@ Parameters n
AS
SQL sentence
GO

Execute stored procedure syntax

EXECUTE The process of Parameters
EXEC The process of Parameters

Stored procedure parameters :

  • Input parameters : Pass in the value to the stored procedure
  • Output parameters : Stored procedure output value , Use output keyword

Execute stored procedures

EXEC The process of ’ value ', value

or

EXEC Stored procedure name Parameters 1 = ’ ’ , Parameters 2 = ’ ’

Two ways , One is to use the form of key value pairs to pass , One is to pass parameters directly in order .

Examples are as follows :

use MySchool
go

 
create proc proc_stuResultParam
	@subject varchar(10),
	@score int
    as
    
    ---- Find this Java OOP  The average score of the test and the information of the people who failed 


    --- Define variables to save the last exam time 
declare @maxDate datetime 





select @maxDate = MAX(ExamDate) from Result
  where SubjectId =(select SubjectId from Subject 
                    where SubjectName = @subject)
 
 
--- Calculate the average score 
select AVG(StudentResult) from Result
	where ExamDate = @maxDate
	and SubjectId = (select SubjectId from Subject 
                    where SubjectName = @subject) 
-- Check the list of students who failed the exam 
select * from Student
		where StudentNo in(
	select StudentNo from Result
	where SubjectId =  (select SubjectId from Subject 
                    where SubjectName = @subject) 
    and ExamDate = @maxDate  
    and StudentResult < @score 
    ) 
    go  
    --  Calling a parameter stored procedure 
    exec dbo.proc_stuResultParam 'Java OOP',94
    
    exec dbo.proc_stuResultParam @subject ='C# oop',@score =80

You can also specify the default value when declaring formal parameters. The default value will be overridden by the new parameter .
When declaring parameters, the parameters with default values should be declared later , Otherwise, you need to add... Before the parameter when passing in the parameter default keyword .

Output parameters

  • When using, you must add... After the attribute output Keyword to indicate that the parameter is an output parameter
  • When receiving an outgoing result, declare a new parameter for receiving

Examples are as follows :

use MySchool
go

 
create proc proc_stuResultParam
	@subject varchar(10), -- Input parameters 
	@score int = 60,
	@count int output -- Output parameters 
    as
    
    ---- Find this Java OOP  The average score of the test and the information of the people who failed 


    --- Define variables to save the last exam time 
declare @maxDate datetime 





select @maxDate = MAX(ExamDate) from Result
  where SubjectId =(select SubjectId from Subject 
                    where SubjectName = @subject)
 
 
--- Calculate the average score 
select AVG(StudentResult) from Result
	where ExamDate = @maxDate
	and SubjectId = (select SubjectId from Subject 
                    where SubjectName = @subject) 
-- Check the list of students who failed the exam 
select * from Student
		where StudentNo in(
	select StudentNo from Result
	where SubjectId =  (select SubjectId from Subject 
                    where SubjectName = @subject) 
    and ExamDate = @maxDate  
    and StudentResult < @score 
    ) 
-- Count the number of people who failed 

select @count = count(StudentNo) from Result
	where SubjectId  =  (select SubjectId from Subject 
                    where SubjectName = @subject) 
    and ExamDate = @maxDate  
    and StudentResult < @score 
    go  
    declare @c int 
    --  Calling a parameter stored procedure 
   --exec dbo.proc_stuResultParam 'Java OOP',80, @c output
   --select @c
    
   exec dbo.proc_stuResultParam @subject ='C# oop',@count = @c output

It can also be used in the same way return , But before you receive the data that's coming out , To receive from a newly declared parameter return The parameters come out , The parameters received in this way are just return The parameters passed out .
Examples are as follows :

use MySchool
go

 
create proc proc_stuResultParam
	@subject varchar(10), -- Input parameters 
	@score int = 60,
	@count int output -- Output parameters 
    as
    
    ---- Find this Java OOP  The average score of the test and the information of the people who failed 


    --- Define variables to save the last exam time 
declare @maxDate datetime 





select @maxDate = MAX(ExamDate) from Result
  where SubjectId =(select SubjectId from Subject 
                    where SubjectName = @subject)
 
 
--- Calculate the average score 
select AVG(StudentResult) from Result
	where ExamDate = @maxDate
	and SubjectId = (select SubjectId from Subject 
                    where SubjectName = @subject) 
-- Check the list of students who failed the exam 
select * from Student
		where StudentNo in(
	select StudentNo from Result
	where SubjectId =  (select SubjectId from Subject 
                    where SubjectName = @subject) 
    and ExamDate = @maxDate  
    and StudentResult < @score 
    ) 
-- Count the number of people who failed 

select @count = count(StudentNo) from Result
	where SubjectId  =  (select SubjectId from Subject 
                    where SubjectName = @subject) 
    and ExamDate = @maxDate  
    and StudentResult < @score 
   -- The stored procedure returns the highest score 
   declare @max int = 0
   select @max = max(StudentResult) from Result
	where SubjectId  =  (select SubjectId from Subject 
                    where SubjectName = @subject) 
    and ExamDate = @maxDate  
    return @max
    go  
    declare @c int
   
    --  Calling a parameter stored procedure 
   --exec dbo.proc_stuResultParam 'Java OOP',80, @c output
   --select @c
    declare @MaxReturnParam int -- By receiving return The value returned by the 
   exec @MaxReturnParam = dbo.proc_stuResultParam @subject ='C# oop',@count = @c output
   select @MaxReturnParam

Custom error message

Use RAISERROR From defining error messages :
RAISERROR(msg_id| msg_str,severity, state WITH option[,…n])
msg_id : stay sysmessages User defined error messages are specified in the system table
msg_str: User defined specific information , The longest 255 Characters
severity: Define the severity level . Users can use the level of 0~18 level

  • 0~10: It won't jump to catch
  • 11-19: Get into catch
  • 20-: Terminate the database connection

state: State of an error ,1 To 127 Between the value of the
option: Indicates whether to log errors to the server error day
Examples are as follows :`

declare @age int 
set @age =1000



if(@age>=0 and @age<=100)
print @age
else
-- Text , error level (0~18 Between ), state (1~127)
raiserror(' Age should be entered 0~100 Between ',16,1)

原网站

版权声明
本文为[MousseIn]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211332353981.html