存储过程的写法与不同

来源:互联网 发布:mac下载iphone应用 编辑:程序博客网 时间:2024/06/04 19:15

下面是个存储过程的应用

 

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:  <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>
 -- Add the parameters for the stored procedure here
 @title nvarchar(100),  --新闻标题
 @content TEXT,         --新闻内容
 @pubUser NVARCHAR(50), --发布人
 @catids varchar(200),  --新闻类别列表,用“:”分割
 @error nvarchar(200) OUTPUT  --用来返回错误信息
AS
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 SET NOCOUNT ON;
 declare @newsid int  --新闻id
 declare @catid varchar(10) --新闻类别id
 declare @pos int  --类别列表中分隔符":"的位置
   
    begin transaction
    begin try
        insert into newscontent(title,[content],pubuser)values(@title,@content,@pubUser)
        set @newsid=@@identity

        while(len(@catids)>0)
        begin
            set @pos=charindex(':',@catids)
   if(@pos<>0)
   begin
    set @catid=substring(@catids,1,@pos-1)
    set @catids=substring(@catids,@pos+1,@pos)
   end
   else
   begin
    set @catid=@catids
    set @catids=''
   end
   insert into newscategory(newsid,catid)values(@newsid,cast(@catid as int))
        end
  commit transaction
  return 0
    end try
 begin catch
  set @error=error_message()
  rollback transaction
  return 1
    end catch
END

 

在存储中语句的内容要写在begin和end之间

例如:

c#中的if语句

if(){};

而存储过程中的if语句

if()

begin 语句  end

 

catch语句写成

begin catch       

//语句

end catch

 

在就是声明变量的方法不一样 用declare @num nvarchar形式 声明

赋值使用set赋值