我正在研究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
在我的if exists部分。如何以正确的方式更改存储过程?
答案 0 :(得分:15)
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
答案 1 :(得分:3)
将它们放在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