如何在触发器中使用变量作为列名

how to use variable as a column name in trigger

我尝试为我的网络数据库创建一些触发器,但这里没有我的触发器的工作代码问题

BEGIN
DECLARE t INT;
DECLARE b INT;
DECLARE ir INT;
DECLARE tgl INT;
DECLARE kol VARCHAR(3);



SET tgl = "(SELECT RIGHT(booking_checkin, 2) FROM pt_bookings WHERE booking_id = NEW.booking.id)";

SET ir = "(SELECT booked_room_id FROM pt_booked_rooms WHERE booking_id = NEW.booking.id)";

SET b = "(SELECT MID(booking_checkin , 6,2) FROM pt_bookings WHERE booking_id = NEW.booking_id)";

SET t = "SELECT IF((SELECT LEFT(booking_checkin, 4) FROM pt_bookings WHERE booking_id = NEW.booking_id) = 2019 ,'0','1')";

SET kol = "d" + tgl;

UPDATE pt_rooms_availabilities
set kol = kol + (SELECT `booking_nights` FROM `pt_bookings` WHERE booking_id = NEW.booking_id)
WHERE room_id = ir AND y = t AND m= b; 
END

问题是 var kol 没有读作列名 也许有人可以帮助我?

无法在触发器中执行此操作。通常,您可以使用 dynamic sql to use variable column names, see e.g. Dynamic conversion of string into column name. This is however not allowed in stored functions or triggers.

您可以使用 if then else 为每种情况使用不同的 insert 语句,例如 if tgl = 7 then update ... set d7 = d7 + ... elseif tgl = 122 then update ... set d122 = d122 + ...

虽然在大多数情况下,您可以而且应该通过 table 设计来避免这种情况。

我不确定你到底想做什么,但你可以只添加一列 tglcode 到你的 table,将那个值存储在那里然后添加 where tglcode = tgl你的 update 声明。看起来您(或您的前任)对存储在列 mt 中的变量 bt 做了类似的事情。

虽然没有更多信息,但很难说这是否是针对您的问题的可行解决方案(或适当的 table 设计)。但是您绝对不能像在触发器中那样使用变量 kol