触发器、存储过程、函数 基本操作(二)
二、存储过程
1. 创建
语法
CREATE PROC [ EDURE ] procedure_name [ ; number ]
[ { @parameter data_type }
[ VARYING ] [ = default ] [ OUTPUT ]
] [ ,...n ]
[ WITH
{ RECOMPILE | ENCRYPTION | RECOMPILE , ENCRYPTION } ]
[ FOR REPLICATION ]
AS sql_statement [ ...n ]
eg:
无参数
create proc sayHello
as
begin
print'Hello World!'
end
exec sayHello
有参数
create procedure sayHello1 @userName varchar(10)
as
begin
print'hello'+@userName+'!'
end
exec sayHello1' baby'
有输出
createproc sayHello2
@userName varchar(10),
@outVal varchar(10)OUTPUT
as
begin
print'hello '+@userName+@outVal+'!'
set@outVal='haha'
end
exec sayHello2 'aa','cc'
declare @rc int,@output varchar(10);
begin
set@output=' 123';
exec@rc=sayHello2 'A',@outputOUTPUT;
print@rc;
print'output = '+@output;
end
默认值
create proc sayHello3
@userName varchar(10),
@val1 varchar(20)='hihao',
@val2 varchar(20)='welcome!'
as
begin
print@userName+''+@val1+''+@val2+'!';
end
declare@rcint;
begin
exec @rc=sayHello3 'hll';
print @rc;
exec @rc=sayHello3 'hll2',' goodNight ';
print @rc;
exec @rc=sayHello3 'hll3',' goodNight ',' bye';
print @rc;
end
指定参数名调用
declare @rcint;
begin
exec @rc=sayHello3 'qq';
print @rc;
exec @rc=sayHello3 'qq2',@val1=' goodMorning ';
print @rc;
exec @rc=sayHello3 'qq3',@val1=' goodMorning ',@val2=' haha';
print @rc;
exec @rc=sayHello3 'qq3',@val2=' haha';
print@rc;
end
返回结果集
create proc resultSet
as
begin
select top(4)*from Teacher;
end
begin
declare @rc int;
exec @rc=resultSet;
print @rc;
end
2. 修改
alter proc sayHello
as
begin
print'Hello World2!'
end
exec sayHello
3. 删除
Drop proc proc_name
4. 查看
查看数据库已有存储过程
use jxcSoftware
go
select * from sysobjects where xtype='P'
查看单个存储过程
exec sp_helptext '存储过程名'