当前位置:网站首页>Stored procedures in sqlserver
Stored procedures in sqlserver
2022-06-24 18:39:00 【MousseIn】
stored procedure
- 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)
边栏推荐
- It is often blocked by R & D and operation? You need to master the 8 steps before realizing the requirements
- Architecture decryption from distributed to microservice: several common microservice architecture schemes
- He "painted" what a smart city should look like with his oars
- Exception: Gradle task assembleDebug failed with exit code 1
- The mixed calculation of rpx and PX in JS by the uniapp applet
- 微服務系統設計——子服務項目構建
- 电源噪声分析
- Creating a new MySQL user in Amazon RDS environment - creating a new MySQL user in Amazon RDS environment
- JS picture switching case
- Cloud service selection of enterprises: comparative analysis of SaaS, PAAS and IAAs
猜你喜欢

Window object

JS local storage

SAP license:sap s/4hana is the answer

Four security issues of low code and no code development

Recommend a distributed JVM monitoring tool, which is very practical!

Several key points for enterprises to pay attention to digital transformation

Why are more and more people studying for doctors? Isn't it more and more difficult to graduate a doctor?

DOM (document object model)

JS deep understanding of scope

(Video + graphics) introduction to machine learning series - Chapter 11 support vector machines
随机推荐
Redis series (3) - sentry highly available
面试算法 - 字符串问题总结
SAP license: ERP for supply chain management and Implementation
ASP. Net hosting uploading file message 500 error in IIS
Project Management Guide: tips, strategies and specific practices
Keep two decimal places
Several key points for enterprises to pay attention to digital transformation
Sword finger offer 10- ii Frog jumping on steps
Interview algorithm - string question summary
BOM(Browser Object Model)
Bisection function template
Monotone stack template
next_ Permutation full permutation function
Digital trend analysis of B2B e-commerce market mode and trading capacity in electronic components industry
Why should state-owned enterprises accelerate the digital transformation
Three indicators to help you measure the effectiveness of digital transformation
Sudoku (easy to understand)
Some knowledge of the beginning of 2022
Architecture decryption from distributed to microservice: several common microservice architecture schemes
Selection (030) - what is the output of the following code?