2012-05-19 3 views
2

J'ai deux tables:Comment créer cette procédure stockée?

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]) 
) 

Je veux faire la procédure suivante:

Je dispose d'un paramètre d'entrée @NewsId.

ÉTAPE 1

  • Si NewsId est NULL: Je veux enregistrer la ligne dans la table (NEWS).
  • Si newsid est défini, je veux mettre à jour la ligne.

ÉTAPE 2

  • Je veux faire l'étape 1 et puis enregistrez l'enregistrement dans une table nommée LOG.
  • INSERT INTO LOG ("Action") VALUES ("insert or update")

Comment puis-je faire ces deux étapes en utilisant la procédure stockée?

Comment faire un pas après la fin réussie et passer à l'étape 2?

+0

Oui. J'ai ajouté une définition de tables. – JohnMalcom

Répondre

2

Voici un échantillon simple pour vous aider à démarrer.

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 

de 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

Comment puis-je protéger une insertion réussie insère un enregistrement dans la table de journal? – JohnMalcom

+0

ne sais pas ce que vous voulez dire. Cherchez-vous le traitement d'erreur de l'insertion des nouvelles ou du journal? –

+0

Oui, pour la gestion des erreurs. Comment puis-je attraper l'erreur? – JohnMalcom

Questions connexes