sqlserver怎么创建存储过程

如题所述

SQL 创建存储过程:

一、基础语法:

create proc | procedure pro_name
    [{@参数数据类型} [=默认值] [output],
     {@参数数据类型} [=默认值] [output],
     ....
    ]
as
    SQL_statements

 

二、常见创建存储过程实例

1、创建不带参数存储过程

create proc proc_get_student
as
select * from student;

执行存储过程:

exec proc_get_student;

2、 带参存储过程

create proc proc_find_stu(@startId int, @endId int)
as
select * from student where id between @startId and @endId

执行存储过程:

exec proc_find_stu 2, 4;

3、 带通配符参数存储过程

create proc proc_findStudentByName(@name varchar(20) = '%j%', @nextName varchar(20) = '%')
as
select * from student where name like @name and name like @nextName;

执行存储过程:

exec proc_findStudentByName;
exec proc_findStudentByName '%o%', 't%';

4、 带输出参数存储过程

create proc proc_getStudentRecord(
@id int, --默认输入参数
@name varchar(20) out, --输出参数
@age varchar(20) output--输入输出参数
)
as
select @name = name, @age = age  from student where id = @id and sex = @age;

执行存储过程:

declare @id int,
@name varchar(20),
@temp varchar(20);
set @id = 7; 
set @temp = 1;
exec proc_getStudentRecord @id, @name out, @temp output;
select @name, @temp;
print @name + '#' + @temp;
温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-03-24
第一步:点击数据库下的“可编程性”,选择“存储过程”,点击鼠标右键,选择“新建存储过程”

第二步:在create PROCEDURE 后 输入存储过程的名字,紧跟着的就是定义存储过程的参数,接下来就可以去编写自己所需要组装的存储过程语句了
注意,怕写的不对,可以执行下,想验证sql语句是否正确,就使用print输出下

第三步:点击上面的执行,存储过程就写好了,要怎么调用呢,在sqlserver的语句查询框中,输入exec 存储过程名 参数,执行就可以了。

END

注意执行exec时,参数的类型,要与建立的存储过程时设置的参数类型一致

更详细:http://jingyan.baidu.com/article/380abd0a4122161d91192c60.html本回答被提问者采纳
第2个回答  2016-03-30
在查询分析器中就可以创建。
create procedure sp_sum_salary
@dept_id varchar(20)
as
--------直接以查询语句输出
select sum(salary)
from tb_employee
where dept_id = @dept_id