如何使用存储过程更新 T-SQL 中的多个值

How to UPDATE multiple values in T-SQL with the stored procedure

我有一个 table 这样的:

CREATE TABLE Ticket
(
    id_Ticket int PRIMARY KEY,
    id_Passengers int,
    id_Schedule int,
    Ticket_Price money,
    Nomer_Mest int
)

声明并执行:

DECLARE @Ticket_Price int, @id_Ticket int;
SET @Ticket_Price = 50 
SET @id_Ticket = 9

EXEC AlterTicket @Ticket_Price, @id_Ticket

这是我的存储过程:

CREATE PROCEDURE AlterTicket
    @Ticket_Price Money, @id_Ticket int, @Nomer_Mest int;
AS
    UPDATE Ticket 
    SET Ticket_Price = @Ticket_Price
    WHERE id_Ticket = @id_Ticket

    UPDATE Ticket 
    SET Nomer_Mest = @Nomer_Mest 
    WHERE id_Ticket = @id_Ticket

我还必须同时为 2 个参数赋值。但是让我们说 我只需要改变Ticket_Price,我不会改变参数 存储过程。

您可以在一次更新中更新多个值:

CREATE PROCEDURE AlterTicket
    @Ticket_Price Money, @id_Ticket int, @Nomer_Mest int;
AS
    UPDATE Ticket 
    SET Ticket_Price = @Ticket_Price, Nomer_Mest = @Nomer_Mest
    WHERE id_Ticket = @id_Ticket;

我将从更改参数的顺序开始,您可以检查 NULL:

CREATE PROCEDURE AlterTicket
    @id_Ticket int, @Nomer_Mest int, @Ticket_Price Money
AS
    UPDATE Ticket 
    SET Ticket_Price = COALESCE(@Ticket_Price, Ticket_Price), Nomer_Mest = COALESCE(@Nomer_Mest, Nomer_Mest) 
    WHERE id_Ticket = @id_Ticket;

调用它:

EXEC AlterTicket @id_Ticket, @Nomer_Mest, NULL;

或:

EXEC AlterTicket @id_Ticket, NULL, @Ticket_Price;

正如我在评论中所说,我也强烈建议考虑使用 decimal 而不是 money

我不确定你是不是这个意思:

CREATE PROCEDURE AlterTicket
    @id_Ticket int, @Ticket_Price Money = null, @Nomer_Mest int = null
AS
begin
  if @Ticket_Price is not null and @Nomer_mest is not null
    UPDATE Ticket 
    SET Ticket_Price = @Ticket_Price, Nomer_Mest = @Nomer_Mest
    WHERE id_Ticket = @id_Ticket;
  else if @Ticket_Price is not null
    UPDATE Ticket 
    SET Ticket_Price = @Ticket_Price
    WHERE id_Ticket = @id_Ticket;
  else if @Nomer_Mest is not null
    UPDATE Ticket 
    SET Nomer_Mest = @Nomer_Mest
    WHERE id_Ticket = @id_Ticket;
end

这里是DBFiddle demo.

这样做的好处是,在一长串参数中,您可以只传递需要的参数。

基于@HoneyBadger 的工作,我会在您的存储过程定义中使用默认值,然后调用它的赋值方法,例如

CREATE PROCEDURE AlterTicket
(
    @id_Ticket int
    , @Nomer_Mest int = null
    , @Ticket_Price Money = null
)
AS
BEGIN
    SET NOCOUNT, XACT_ABORT ON;

    UPDATE Ticket SET
        Ticket_Price = COALESCE(@Ticket_Price, Ticket_Price)
        , Nomer_Mest = COALESCE(@Nomer_Mest, Nomer_Mest) 
    WHERE id_Ticket = @id_Ticket;

    RETURN 0;
END;

调用它:

EXEC AlterTicket @id_Ticket = @id_Ticket, @Nomer_Mest = @Nomer_Nest;

或者:

EXEC AlterTicket @id_Ticket = @id_Ticket, @Ticket_Price = @Ticket_Price;

这种调用存储过程的形式有两个好处:

  1. 您不必正确设置参数的顺序。
  2. 如果您以后需要添加新参数,则不必更新对存储过程的每个引用。