如何创建此存储过程?

时间:2012-05-19 07:13:22

标签: sql-server stored-procedures transactions

我有两张桌子:

CREATE TABLE [NEWS]
(
    [ID]      INT IDENTITY(1,1) NOT NULL,
    [TITLE]   VARCHAR(500) NULL,
    [CONTENT] VARCHAR(800) NULL,
    [CREATED] DATETIME DEFAULT(GETDATE())

    PRIMARY KEY ([ID])
)

CREATE TABLE [LOG]
(
    [ID]      INT IDENTITY(1,1) NOT NULL,
    [ACTION]  VARCHAR(500) NULL,
    [CREATED] DATETIME DEFAULT(GETDATE())

    PRIMARY KEY ([ID])
)

我想执行以下程序:

我有一个输入参数@NewsId

第1步

  • 如果NewsIdNULL:我想将该行保存到表格中NEWS)。
  • 如果定义了newsid,那么我想更新该行。

第2步

  • 我想执行第1步,然后将记录保存到名为LOG
  • 的表中
  • INSERT INTO LOG ("Action") VALUES ("insert or update")

如何使用存储过程执行这两个步骤?

成功完成后如何进行一步并转到第2步?

1 个答案:

答案 0 :(得分:2)

这是一个简单的示例,可以帮助您前进。

create procedure MyProc (@NewsId int) as
Begin

   -- you should really pass these in?
   declare @title   varchar(500) = 'A title'
   declare @content varchar(800) = 'A piece of content'


   if @NewsId is null
   begin

     Begin Try 
       insert into News (Title, Content)  values (@title, @content)

       -- get the new id just inserted
       set @NewsId = SCOPE_IDENTITY()

       insert into Log (Action) values ('insert')
     End Try

     Begin Catch
      .... handle error 
     end catch

   end
   else
   begin 
        update News set Title = @title, Content = @content
        where id = @NewsId
       insert into Log (Action) values ('update')

   end

end

来自CodeProject

Begin Try 
 The_Query_for_which_we_need_to_do_the_ Error_Handling 
End Try 
Begin Catch 

  If there is some error in the query within the Try block, this flow 
  will be passed to this Catch block. 

End catch