美文网首页SQL技术文
sql server存储过程入门

sql server存储过程入门

作者: 三思吾 | 来源:发表于2017-04-06 16:25 被阅读344次

    创建存储过程的基本语法:(无参数存储过程)

    create procedure p1
    as
    begin
    sql 语句
    end
    go
    

    其中begin 和 end可以省略
    在sql server服务器端执行的语句为:exec p1


    创建只有输入参数的存储过程:

    create procedure p1(@id int)
    as
    select * from 表1 where id=@id
    go
    

    在sql server服务器端执行的语句为:exec p1 1
    直接在存储过程名后面加上要传入的参数即可


    创建带有一个输入参数,一个输出参数的存储过程:
    传入参数的后面需要加上out关键字,
    如果不加关键字,默认为传入参数

    create procedure p1(@id int,@studentname varchar(200) out)
    as
    select @studentname= name from 表1 where id=@id
    go
    

    在sql server服务器端执行的语句为:

    declare @StudentName as nvarchar(200)  -- 声明输出参数
    exec p1 1,@StudentName output
    select @StudentName  --select语句可以查看结果```
    直接在存储过程名后面加上要传入的参数和输出参数并加上output关键字即可
    *注意:*输出参数不要和存储过程定义里面的输出参数重名
    
    ---
    **创建带有多个输出参数的存储过程**
    和带有一个输出参数的是类似的写法
    

    create procedure p1(@id int,@studentname varchar(200) out@studenttele varchar(200) out)
    as
    select @studentname= name,@studenttele=tele from 表1 where id=@id
    go

    declare @StudentName as nvarchar(200) -- 声明第一个输出参数
    declare @StudentTele as nvarchar(200) -- 声明第二个输出参数
    exec p1 1,@StudentName output,@StudentTele output
    select @StudentName, @StudentTele --select语句可以查看结果```


    有时候,我们创建前需要判定是否存在,存在则删除,只需要在创建之前执行如下sql:

     if exists(select * from sysobjects where name='p1' and type='P') 
     drop procedure p1
     go
    

    修改存储过程的sql:

    alter procedure p1
    as
    sql语句
    go
    

    相关文章

      网友评论

        本文标题:sql server存储过程入门

        本文链接:https://www.haomeiwen.com/subject/quafattx.html