Sql Server存储过程详解

 

存储过程--查询:

Sql Server存储过程详解

if (exists (select * from sys.objects where name = 'GetUser')) drop proc GetUser   --判断存储过程是否存在,存在则删除然后重建。
go
create proc GetUser  --创建存储过程 GetUser
@Id int --参数
as 
set nocount on;  --不返回计数,提高应用程序性能
begin --开始
    select * from [dbo].[User] where [email protected]  --执行sql语句
end;--结束

Sql Server存储过程详解

调用存储过程

EXEC GetUser 1;

执行结果

Sql Server存储过程详解

 

 存储过程--修改:

Sql Server存储过程详解

if (exists (select * from sys.objects where name = 'UpdateUser')) drop proc UpdateUser   --判断存储过程是否存在,存在则删除然后重建。
go
create proc UpdateUser  --创建存储过程 GetUser
@Id int, --参数
@Name varchar(255),--参数
@Sex int, --参数
@Age int, --参数
@Birthday date --参数
as 
set nocount on;  --不返回计数,提高应用程序性能
begin --开始     
    UPDATE [dbo].[UserInfo] SET [Name][email protected],[Sex][email protected], [Age][email protected],[Birthday][email protected] WHERE ([Id][email protected]) --执行sql语句
end;--结束

Sql Server存储过程详解

调用存储过程:

EXEC UpdateUser 1,'赵大1',2,222,'1994-07-16 11:36:27';

执行结果:

Sql Server存储过程详解

 

存储过程分页

Sql Server存储过程详解

if (exists (select * from sys.objects where name = 'Page_UserInfo')) drop proc Page_UserInfo   --判断存储过程是否存在,存在则删除然后重建。
go
create proc Page_UserInfo  --创建存储过程 
    @name nvarchar(255),--用户名
    @pageindex int,--第几页
    @pagesize int--一页多少条
as 
set nocount on;  --不返回计数,提高应用程序性能
begin --开始
  declare @pagebefore int;--创建页数
    declare @pagerear int;--创建页数
  declare @condition nvarchar(2000);  --创建where条件
    set @[email protected]*@pageindex; --起始页
    set @[email protected][email protected];--结束页
    set @condition=' where 1=1 ';
    if(@name<>'')
    set @[email protected]+' and name like ''%'[email protected]+'%''';
  --创建一个虚拟表插入UserInfo表数据
  --获取分页数据
  --获取总数
    exec('
    declare @table table(
    iid int identity,
    Id int,
    Name nvarchar(20),
    Sex int,
    Age int,
    Birthday datetime
    )
    insert @table
    select * from UserInfo '[email protected]+' order by Id desc  
    select * from @table where iid>'[email protected]+' and iid<='[email protected]+'
    select count(*) as rows from @table;');
end;--结束

Sql Server存储过程详解

 

调用方式:

EXEC Page_UserInfo  '' ,1,10

调用结果:

Sql Server存储过程详解Sql Server存储过程详解