SQL Server的存储过程怎么写?
SQL server中如何存储:
首先准备数据,测试存储过程
use ssqadm;
创建测试books表
create table books_test ( book_id int identity(1,1) primary key,
book_name varchar(20),book_price float,book_auth varchar(10));
插入测试数据
insert into books_test (book_name,book_price,book_auth)values
('论语',25.6,'孔子'),
('天龙八部',25.6,'金庸'),
('雪山飞狐',32.7,'金庸'),
('平凡的世界',35.8,'路遥'),
('史记',54.8,'司马迁');
select * from books_test;*/
创建无参存储过程
if (exists (select * from sys.objects where name = 'getAllBooks'))
drop proc getAllBooks
go
create procedure getAllBooks
as
begin
select * from books_test;
调用,执行存储过程
exec getAllBooks;
end
go
修改存储过程
alter procedure getallbooks
as
select book_name from books_test;
修改存储过程的名称
sp_rename getallbooks,proc_get_allbooks;
go
exec proc_get_allbooks;
go
创建带参数的存储过程
use ssqadm
go
if (exists (select * from sys.objects where name = 'searchbooks'))
drop proc searchbooks
exec searchbooks
执行存储searchbooks得到如下结果:
go
create procedure searchbooks (@bookid int)--括号里面是
as
begin
declare @book_id int;定义一个标量变量,只是保证存储过程的完整性,在本存储是多此一举的。
set @book_id = @bookid;
select* from books_test where book_id = @book_id;
end;
go
-- exec searchbooks
执行存储searchbooks得到如下结果:
创建带两个参数的存储过程
use ssqadm
go
if (exists (select * from sys.objects where name = 'book_test2'))
drop proc book_test2
exec book_test2
执行存储book_test2得到如下结果:
go
create procedure book_test2
(@bookid int,@bookname varchar(20))括号里面是
as
begin
declare @book_id int;
定义一个标量变量,只是保证存储过程的完整性,在本存储是多此一举的。
declare @book_name varchar(20);
set @book_id = @bookid;
set @book_name = @bookname;
select* from books_test where book_id =
@book_id and book_name = @book_name;
end;
go
exec book_test2
扩展资料:
SQL Server中查询存储命令子句:
USE [SSQADM]
Use 是跳转到哪个数据库,对这个数据库进行操作。
GO
GO向 SQL Server 实用工具发出一批 Transact-SQL 语句结束的信号,相当于提交上面的SQL语句。
GO是把t-sql语句分批次执行
(一步成功了才会执行下一步,即一步一个GO)
/****** Object: StoredProcedure [dbo].[PROC_four_five_hr]
Script Date: 07/30/2018 13:44:55 ******/
SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ON
标签:SQL,Server,存储