sql-server - 如何创建这个存储过程?

标签 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(“操作”)VALUES(“插入或更新”)

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

成功完成后如何进行第1步并转到第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 

关于sql-server - 如何创建这个存储过程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10663166/

相关文章:

sql-server - 在 SQL Server 中打印文本字段内容的最简单方法

c# - Dapper 函数不映射存储过程中的字符串值,但正确映射其他值

transactions - SSIS TransactionOption Required 导致错误(全部在本地机器上)

mysql - 优化插入的最佳方法

sql-server - 对于存储在 SQL Azure 中的点对点距离,最佳数据库表设计是什么

SQL 字符串连接,仅当 column 不为 null 时才以 ',' 分隔

c# - 如何使用 LINQ 和 Entity Framework 查询具有 'AND' 条件的多对多关系

MySQL在另一个过程中调用一个过程并将值插入临时表

mysql - 多个查询 VS 存储过程

spring - 在声明式事务管理中,无论事务是提交还是回滚,如何在 Spring 中获取事务信息?