学习存储过程(1)
存储过程说白了就是一堆 SQL 的合并。中间加了点逻辑控制。
用户自定义存储过程create proc | procedure pro_name
    [{@参数数据类型} [=默认值] [output],
     {@参数数据类型} [=默认值] [output],
     ....
    ]
as
    SQL_statements
创建存储过程
Create procedure  sp_name      //sp_name 自己给存储过程去的名称
Begin
……
End
Create Proc dbo.存储过程名
    存储过程参数
    AS
    执行语句
    RETURN
    执行存储过程
    GO
Eg:
-- 要创建存储过程的数据库
Use Test
-- 判断要创建的存储过程名是否存在
if Exists(Select name From sysobjects Where name='csp_AddInfo' And
type='P')
-- 删除存储过程
Drop Procedure dbo.csp_AddInfo
Go
-- 创建存储过程
Create Proc dbo.csp_AddInfo
-- 存储过程参数
@UserName varchar(16),
@Pwd varchar(50),
@Age smallint,
@Sex varchar(6)
AS
-- 存储过程语句体
insert into Uname (UserName,Pwd,Age,Sex)
values (@UserName,@Pwd,@Age,@Sex)
RETURN
-- 执行
GO
-- 执行存储过程
EXEC csp_AddInfo 'Junn.A','123456',20,'男'
--创建存储过程
if (exists (select * from sys.objects where name = 'proc_get_student'))
    drop proc proc_get_student
go
create proc proc_get_student
as
    select * from student;
--调用、执行存储过程
exec proc_get_student;
存储过程说白了就是一堆 SQL 的合并。中间加了点逻辑控制。
存储过程运行流程
 
创建不带参数存储过程
--创建存储过程
if (exists (select * from sys.objects where name = 'proc_get_student'))
    drop proc proc_get_student
  
create proc proc_get_student
as
    select * from student;
  结果:
--调用、执行存储过程
exec proc_get_student;
  查询结果:
 
带参存储过程
if (object_id('proc_find_stu', 'P') is not null)
    drop proc proc_find_stu
go
create proc proc_find_stu(@startId int, @endId int)
as
    select * from student where id between @startId and @endId
go
exec proc_find_stu 2, 4;
  执行结果:
2	赵姳        	17        	男         
3	张曼        	18        	女         
4	张立        	19        	女
 

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号