带有数据表参数的存储过程 - 如何在不循环数据表的情况下执行条件更新

问题描述 投票:0回答:1

我有一个存储过程,它采用 DataTable(int Id)作为参数。我使用数据表执行更新。执行此操作后,我想添加进一步的条件更新,这可能会根据计算值对某些记录产生不同的影响,但不知道如何在不使用游标循环遍历数据表中的 Id 的情况下执行此操作 - 是否有更好的方法方式?

这是伪存储过程代码

spEvents_AddRemovePlaces_TVP
@DataTable AS dbo.TVP_IntIds READONLY
,@NumPlaces int

--use the datatable to perform an update to the number of places available for an event
update [events] SET 
NumberOfPlacesBooked+=@NumPlaces
WHERE Id in (select Id from @DataTable)

--next check if there are any places left for each record and perform an update (Crucially ONLY if required on a per record basis)

-- at the moment I am using a cursor and doing the following

DECLARE @NumPlacesLeft int
--Loop through the DataTable and perform a check (loop code excluded for clarity)

-- ** START LOOP **

SET @NumPlacesLeft = (select SUM(NumberOfPlacesAvailable - NumberOfPlacesBooked) as totalPlacesLeft from [events] where Id=@EventId )

IF @NumPlacesLeft <=0
    -- update db flag to HAS NO places left
    update [events] set IsFullyBooked=1 where Id=@EventId
ELSE
    -- update db flag to HAS places left
    update [events] set IsFullyBooked=0 where Id=@EventId

-- ** END LOOP **

有没有更好的方法来做到这一点,而不必使用游标循环?

谢谢你

sql-server t-sql table-valued-parameters
1个回答
0
投票

随心所欲地做。例如

create table t (id int,NumberOfPlacesAvailable int, NumberOfPlacesBooked int, isfullybooked int);

insert into t values (1,10,5,null),(2,10,10,null);

update t 
set NumberOfPlacesBooked = NumberOfPlacesBooked + 5,
    isfullybooked = case when NumberOfPlacesAvailable - (NumberOfPlacesBooked +5) = 0 then 1 else 0 end
where id = 1

select * from t

id          NumberOfPlacesAvailable NumberOfPlacesBooked isfullybooked
----------- ----------------------- -------------------- -------------
1           10                      10                   1
2           10                      10                   NULL
© www.soinside.com 2019 - 2024. All rights reserved.