使用ONE更新语句更新SQL Server中的多个数据

时间:2018-02-10 15:19:29

标签: sql-server

我一次将多条记录保存到我的SQL Server表中,准确地将5条记录保存到。

数据保存得很好,但我不确定如何一次更新所有这些记录。

这就是我所拥有的。请帮我详细说明如何更新我的SQL Server程序部分,以便一次更新所有这些记录。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[sp_UserInsertUpdate]
    @UserID INT,
    @Monday VARCHAR(100),
    @MondayAM BIT,
    @MondayPM BIT,
    @MondayNA BIT,
    @Tuesday VARCHAR(100),
    @TuesdayAM BIT,
    @TuesdayPM BIT,
    @TuesdayNA BIT,
    @Wednesday VARCHAR(100),
    @WednesdayAM BIT,
    @WednesdayPM BIT,
    @WednesdayNA BIT,
    @Thursday VARCHAR(100),
    @ThursdayAM BIT,
    @ThursdayPM BIT,
    @ThursdayNA BIT,
    @Friday VARCHAR(100),
    @FridayAM BIT,
    @FridayPM BIT,
    @FridayNA BIT
AS
BEGIN
    IF (@UserID = 0)
    BEGIN
        INSERT INTO tb_UserAvailability (Day, AM, PM, NotAvailable)
        VALUES (@Monday, @MondayAM, @MondayPM, @MondayNA),
               (@Tuesday, @TuesdayAM, @TuesdayPM, @TuesdayNA),
               (@Wednesday, @WednesdayAM, @WednesdayPM, @WednesdayNA),
               (@Thursday, @ThursdayAM, @ThursdayPM, @ThursdayNA),
               (@Friday, @FridayAM, @FridayPM, @FridayNA)
    END
    ELSE
    BEGIN   
        UPDATE [dbo].[tb_UserAvailability]
        SET -- Update statement here. Need help.
        WHERE UserID = @UserID
    END
END

谢谢

1 个答案:

答案 0 :(得分:1)

你可以使用它。

UPDATE T SET 
    T.AM = SRC.AM,
    T.PM = SRC.PM,
    T.NotAvailable = SRC.NotAvailable
FROM [dbo].[tb_UserAvailability] T
INNER JOIN 
    (VALUES
        (@Monday, @MondayAM, @MondayPM, @MondayNA),
        (@Tuesday, @TuesdayAM, @TuesdayPM, @TuesdayNA),
        (@Wednesday, @WednesdayAM, @WednesdayPM, @WednesdayNA),
        (@Thursday, @ThursdayAM, @ThursdayPM, @ThursdayNA),
        (@Friday, @FridayAM, @FridayPM, @FridayNA) ) AS SRC (Day, AM, PM, NotAvailable) ON T.Day = SRC.Day
Where T.UserID = @UserID