Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 967
Sjemmie Avatar asked Mar 12 '10 12:03

Sjemmie


People also ask

Can a stored procedure have multiple statements?

Each procedure has one or more statements. In our case, these are SQL statements. So, you can write a procedure that will – insert new data, update or delete existing, retrieve data using the SELECT statement. And even better, you can combine more (different statements) in the stored procedures.

How do I run multiple SQL statements in SQL?

To run a query with multiple statements, ensure that each statement is separated by a semicolon; then set the DSQEC_RUN_MQ global variable to 1 and run the query. When the variable is set to zero, all statements after the first semicolon are ignored.


1 Answers

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
like image 158
Sparky Avatar answered Nov 15 '22 07:11

Sparky