【发布时间】:2021-12-23 00:20:31
【问题描述】:
对于像这样的表
create table Stations_in_route
(
ID_station_in_route int primary key,
ID_route int,
ID_station int,
Number_in_route int not null
)
有以下触发器在向路由添加新行后更改 Number_in_route 列中的值。路线中的号码列表必须保持一致。
create trigger stations_in_route_after_insert on Stations_in_route
after insert
as
if exists
(select *from Stations_in_route
where Stations_in_route.ID_station_in_route not in (select ID_station_in_route from inserted)
and Stations_in_route.ID_route in (select ID_route from inserted)
and Stations_in_route.Number_in_route in (select Number_in_route from inserted))
begin
update Stations_in_route
set Number_in_route = Number_in_route + 1
where Stations_in_route.ID_station_in_route not in (select ID_station_in_route from inserted)
and Stations_in_route.ID_route in (select ID_route from inserted)
and Stations_in_route.Number_in_route >= (select Number_in_route from inserted where Stations_in_route.ID_route = inserted.ID_route)
end
如果执行插入到一个 ID_route 中,此触发器将引发错误:
子查询返回超过 1 个值。当子查询跟随 =、!=、、>= 或子查询用作表达式时,这是不允许的。
例如,
Insert into Stations_in_route values(25, 4, 11, 3),(26, 4, 10, 5)
如何解决?
| ID_station_in_route | ID_route | ID_station | Number_in_route |
|---|---|---|---|
| 1 | 4 | 1 | 1 |
| 2 | 4 | 2 | 2 |
| 3 | 4 | 3 | 3 |
| 4 | 4 | 4 | 4 |
| 5 | 4 | 5 | 5 |
| 6 | 4 | 6 | 6 |
| 7 | 4 | 7 | 7 |
| 8 | 4 | 8 | 8 |
我希望添加后的列表会变成这样
| ID_station_in_route | ID_route | ID_station | Number_in_route |
|---|---|---|---|
| 1 | 4 | 1 | 1 |
| 2 | 4 | 2 | 2 |
| 25 | 4 | 11 | 3 |
| 3 | 4 | 3 | 4 |
| 26 | 4 | 10 | 5 |
| 4 | 4 | 4 | 6 |
| 5 | 4 | 5 | 7 |
| 6 | 4 | 6 | 8 |
| 7 | 4 | 7 | 9 |
| 8 | 4 | 8 | 10 |
这不是整张桌子,因为还有其他路线
【问题讨论】:
-
“这个触发器会抛出一个错误”,错误是什么?如果我运行上述内容,我不会收到任何错误:db<>fiddle
-
@Larnu 子查询返回超过 1 个值。当子查询跟随 =、!=、、>= 或子查询用作表达式时,这是不允许的。即添加到同一条路线时它不起作用
-
那是由于触发器中
WHERE中的最后一个子句;该查询只能返回一个标量值。然而,你给我们的 SQL 并没有产生那个错误。 -
@AaronBertrand 我添加了一个示例。我认为我将停止添加重复项。我将回滚更新。
-
仍然不清楚如果两个新行都被赋予相同的位置(例如 3)会发生什么,是否有其他因素迫使其中一个获胜?此外,一般来说,如果您将插入限制为单行,那么它可能更有意义,并且对于更简单得多的触发器,那么逻辑就是
number_in_route + 1 where number_in_route > new_number_in_route。
标签: sql sql-server database triggers