views:

57

answers:

2

I'm working on SQL server 2005 and I have a very simple stored procedure:

create PROCEDURE [dbo].[tblTabel_Insert] 
@ID int,
@Code nvarchar(50) = null
AS
    SET NOCOUNT ON;

  IF  EXISTS (SELECT ID, code FROM tblTabel WHERE ID = @ID and code = @Code) 
    UPDATE tblTabel SET ID = @ID,code = @Code WHERE ID = @ID

ELSE
BEGIN

INSERT INTO tblTabel (ID,code) VALUES ( @ID ,@Code);
END

My question is: is it posible to have multiple queries in my stored procedure ? I want to add the lines

UPDATE tblTabelB SET ID = @ID,code = @Code WHERE ID = @ID
UPDATE tblTabelC SET ID = @ID,code = @Code WHERE ID = @ID

in my if exists section. How do I change my stored procedure in the correct way ?

+11  A: 
IF  EXISTS (SELECT ID, code FROM tblTabel WHERE ID = @ID and code = @Code) 
BEGIN
    UPDATE tblTabel SET ID = @ID,code = @Code WHERE ID = @ID
    UPDATE tblTabelB SET ID = @ID,code = @Code WHERE ID = @ID
    UPDATE tblTabelC SET ID = @ID,code = @Code WHERE ID = @ID
END
Sparky
its that simple ?
Sjemmie
Yes, it is that simple.
Welbog
@Sjemmie: That's the point of having a stored procedure. You can use conditionals, make calculations, have multiple inserts, deletes, updates, whatever you want. :)
Theresa
+2  A: 

Just put them between BEGIN and END

IF  EXISTS (SELECT ID, code FROM tblTabel WHERE ID = @ID and code = @Code) 
BEGIN
    UPDATE tblTabel SET ID = @ID,code = @Code WHERE ID = @ID
   UPDATE tblTabelB SET ID = @ID,code = @Code WHERE ID = @ID
    UPDATE tblTabelC SET ID = @ID,code = @Code WHERE ID = @ID

END

ELSE
BEGIN

INSERT INTO tblTabel (ID,code) VALUES ( @ID ,@Code);
END
John Nolan