加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

使用存储过程操作数据表

发布时间:2020-12-12 12:55:44 所属栏目:MsSql教程 来源:网络整理
导读:go use db_Test;if exists (select * from sysobjects where name='book')drop table book;create table book(bookId int primary key,bookName char(20),bookPrice float,publishTime date);--创建存储过程,向book表中插入10条数据goif exists (select * fr
go 
use db_Test;
if exists (select * from sysobjects where name='book')
drop table book;
create table book(
	bookId int primary key,bookName char(20),bookPrice float,publishTime date
);
--创建存储过程,向book表中插入10条数据
go
if exists (select * from sysobjects where name='addBook')
drop procedure addBook;
go
create procedure addBook as
begin
	declare @i int;
	set @i=1;
	while(@i<10)
	begin
		--cast 将一个表达式转化成另外一个类型
		insert into book select @i,'book '+cast(@i as CHAR(1)),(10+@i)/10.0,GETDATE();
		set @i=@i+1;
	end
end
go
--执行存储过程
exec addBook;

--创建带参数的存储过程:@id表示所借书ID @money表示钱,result 表示借书结果
if exists(select * from sysobjects where name='borrowBook')
drop procedure borrowBook;
go
create procedure borrowBook @id int,@money float,@result bit output as
begin
	declare @bookPrice float;
	--获取所借书本的价格
	select @bookPrice=bookPrice from book where bookId=@id;
	if(@money>=@bookPrice)
		begin
		set @result=1;
		print '可以借书';
		end
	else
		begin
		set @result=0;
		print '不能借书';
		end
end 
go
--执行存储过程
declare @result bit;
--使用output 返回参数
exec borrowBook 1,1.3,@result output;
select case 
			when @result=0 then '不能借书'
			when @result=1 then '可以借书' end as '能否借书';

--修改存储过程:将borrowBook的返回值的类型改为char
go
alter procedure borrowBook @id int,@result char(20) output as
begin
	declare @bookPrice float;
	--获取所借书本的价格
	select @bookPrice=bookPrice from book where bookId=@id;
	if(@money>=@bookPrice)
		begin
		set @result='可以借书';
		end
	else
		begin
		set @result='不能借书';
		end
end 
go
declare @re char(20);
exec borrowBook 1,1.2,@re output;
select @re as '能否借书';

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读