How to fire trigger in SQL Server if in a row 2 column values are the same?
In my table there are 3 columns id
, capacity
, taken
and the table has some rows. If taken
is equal to capacity
, then trigger should fire. I wrote the trigger shown below, but it says "subquery returned more than 1 value" - this is not permitted.
ALTER TRIGGER [dbo].[sectionTrigger1]
ON [dbo].[tblTestCapacity]
FOR UPDATE
AS
BEGIN
SET NOCOUNT ON
IF (SELECT (Capacity-SeatTaken) FROM tblTestCapacity) = 0
BEGIN
INSERT INTO tblTest(sectionid, courseid, seatcapacity, seattaken)
SELECT sectionid, courseid, seatcapacity, seattaken
FROM tblTest
END
END
inside a trigger you should use the inserted
table, which will hold all updated rows
something like this maybe ?
INSERT INTO tblTest(sectionid, courseid, seatcapacity, seattaken)
SELECT i.sectionid, i.courseid, i.seatcapacity, i.seattaken
FROM inserted i
where (i.Capacity - i.SeatTaken) = 0
notice you dont need the IF
anymore because it is already in the WHERE
clause
EDIT
IF you want to do something else when (i.Capacity - i.SeatTaken) = 0
you can use the same query
if exists ( SELECT i.sectionid, i.courseid, i.seatcapacity, i.seattaken
FROM inserted i
where (i.Capacity - i.SeatTaken) = 0
)
begin
-- do here your code if any row exists with this condition
-- you could for example throw an exception here
THROW 51000, 'your message here.', 1;
end
EDIT
if your goal is to restrict 2 columns in the table from having the same value, you can also add a constraint.
This way you dont even need a trigger
This is the best option, if all you need is prevent 2 columns from having the same value
alter table tblTestCapacity
add constraint CH_Doubles check (Capacity <> SeatTaken)
if both or one column can be null, you have to add a little more
alter table tblTestCapacity
add constraint CH_Doubles check (isnull(Capacity, -1) <> isnull(SeatTaken, -1))
The last alter statement is not tested, not sure if sql-server allows this
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.