1、常用系统存储过程及使用语法:
exec sp_databases; --查看数据库
exec sp_tables; --查看表
exec sp_columns student;--查看列
exec sp_helpIndex student;--查看索引
exec sp_helpConstraint student;--约束
exec sp_stored_procedures;
exec sp_helptext ‘sp_stored_procedures‘;--查看存储过程创建、定义语句
exec sp_rename student, stuInfo;--修改表、索引、列的名称
exec sp_renamedb myTempDB, myDB;--更改数据库名称
exec sp_defaultdb ‘master‘, ‘myDB‘;--更改登录名的默认数据库
exec sp_helpdb;--数据库帮助,查询数据库信息
exec sp_helpdb master;
2、用户自定义存储过程
2.1 创建不带参数存储过程:
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;
2.2 带输入参数存储过程
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.3 有输入与输出参数的存储过程
create proc GetCommentCount
@newsid int,
@count int output
as
select @count=count(*) from Comment where [email protected]
--调用方法
declare @newsid int,
@count int;
set @newsid = 7;
exec GetCommentCount @newsid, @count output;
select @count;
print @count;
2.4 返回单个值的函数
create function MyFunction
(@newsid int)
returns int
as
begin
declare @count int
select @count=count(*) from Comment where [email protected]
return @count
end
--调用方法
declare @count int
exec @count=MyFunction 2
print @count
2.5 分页存储过程
--存储过程、row_number完成分页
if (object_id(‘pro_page‘, ‘P‘) is not null)
drop proc proc_cursor
go
create proc pro_page
@startIndex int,
@endIndex int
as
select count(*) from product
;
select * from (
select row_number() over(order by pid) as rowId, * from product
) temp
where temp.rowId between @startIndex and @endIndex
go
--调用方法
exec pro_page 1, 4
--分页存储过程
if (object_id(‘pro_page‘, ‘P‘) is not null)
drop proc pro_stu
go
create procedure pro_stu(
@pageIndex int,
@pageSize int
)
as
declare @startRow int, @endRow int
set @startRow = (@pageIndex - 1) * @pageSize +1
set @endRow = @startRow + @pageSize -1
select * from (
select *, row_number() over (order by id asc) as number from student
) t
where t.number between @startRow and @endRow;
--调用方法
exec pro_stu 2, 2;