一尘不染

SQL和存储过程中的多个语句

sql

我正在使用SQL Server 2005,并且有一个非常简单的存储过程:

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

我的问题是:在存储过程中可以有多个查询吗?我要添加行

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

在我的“如果存在”部分。如何以正确的方式更改存储过程?


阅读 143

收藏
2021-05-23

共1个答案

一尘不染

只需将它们放在BEGIN和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
2021-05-23