SQL查询更新并在表中插入数据

时间:2015-09-08 08:00:56

标签: sql sql-server

我正在尝试更新我的表格,我想在它什么也不做之前检查是否有记录,如果它有所不同则更改它,如果不存在则插入新表格,这是我的表格字段:< / p>

id  res-id   req-id   IsActive
--  ------   ------   --------

这是我的存储过程:

@Res_id int,
@Opt_id int,
@IsActive int
AS 
SET NOCOUNT ON 
SET XACT_ABORT ON  

BEGIN
IF EXISTS (SELECT * FROM [dbo].[res_opt_junc]
            WHERE [Res_id]=@Res_id AND [Opt_id]=@Opt_id AND [IsActive]=1 AND          @IsActive=1)
        BEGIN
        RETURN;
        END; 

ELSE IF EXISTS (SELECT * FROM [dbo].[res_opt_junc] 
            WHERE [Res_id]=@Res_id AND [Opt_id]=@Opt_id AND [IsActive]=0 AND @IsActive=1)
        BEGIN
            UPDATE [dbo].[res_opt_junc]
            SET    [Res_id] = @Res_id, [Opt_id] = @Opt_id, [IsActive] = @IsActive
            WHERE  [Res_id]=@Res_id AND [Opt_id]=@Opt_id AND [IsActive]=0 AND @IsActive=1           
        RETURN;
        END;
ELSE IF EXISTS (SELECT * FROM [dbo].[res_opt_junc] 
            WHERE [Res_id]=@Res_id AND [Opt_id]=@Opt_id AND [IsActive]=1 AND @IsActive=0)
        BEGIN
            UPDATE [dbo].[res_opt_junc]
            SET    [Res_id] = @Res_id, [Opt_id] = @Opt_id, [IsActive] = @IsActive
            WHERE  [Res_id]=@Res_id AND [Opt_id]=@Opt_id AND [IsActive]=1 AND @IsActive=0
            RETURN;
        END;
ELSE IF NOT EXISTS (SELECT * FROM [dbo].[res_opt_junc]
            WHERE [Res_id]=@Res_id AND [Opt_id]=@Opt_id)
        BEGIN
            INSERT INTO [dbo].[res_opt_junc] ([Res_id],[Opt_id],[IsActive])
            VALUES (@Res_id , @Opt_id  , @IsActive);
            RETURN;
        END;
END

我不知道为什么表格中的数据变得不那么重要了;

1 个答案:

答案 0 :(得分:2)

MERGE语句听起来像是工作的工具。

示例:

MERGE [dbo].[res_opt_junc] roj
USING (SELECT @Res_id AS Res_id, @Opt_id AS Opt_id, @IsActive AS IsActive) AS nv
ON roj.Res_id = nv.Res_id AND roj.Opt_id = nv.Opt_Id
WHEN MATCHED THEN
    UPDATE SET roj.IsActive = nv.IsActive
WHEN NOT MATCHED THEN
    INSERT (Res_id, Opt_id, IsActive) VALUES (nv.Res_id, nv.Opt_id, nv.IsActive)
;

当然,我认为Res_idOpt_id是主键的组成部分。