简体   繁体   中英

SQL and multiple statements in stored procedure

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM