2012-05-19 93 views
2

我有两个表:如何创建此存储过程?

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

STEP 1

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

STEP 2

  • 我想要做的步骤1中,然后将记录保存到一个名为LOG表。
  • INSERT INTO LOG ("Action") VALUES ("insert or update")

我能如何使用存储过程,这两个步骤?

如何在成功完成后再进入第2步?

+0

是。我添加了一个定义表。 – JohnMalcom

回答

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 
+0

成功插入插入记录到日志表后,如何保护该插入? – JohnMalcom

+0

不确定你的意思。正在寻找新闻插件或日志的错误处理? –

+0

是的,用于错误处理。我如何发现错误? – JohnMalcom