gpt4 book ai didi

mysql - 如何将 mysql 触发器转换/迁移到 Sql Server 触发器

转载 作者:行者123 更新时间:2023-11-30 00:14:43 25 4
gpt4 key购买 nike

我在 mysql 中做了一个触发器,总是在输入值小于设置值时发出警报。但现在我需要它在 SQL SERVER 中完成。

如果有人能帮助我将 mysql 触发器转换为 SQL Server 触发器,我将不胜感激。

感谢大家。

<小时/>

我的触发器是:

DELIMITER $$
create TRIGGER alert
AFTER INSERT ON records
FOR EACH ROW
begin
Set @comp=0;
Set @tempmax=0;
Set @tempmin=0;

select lim_inf_temp into @tempmin from sensores where idSensor=NEW.idSensor;


Set @maxidAlarme=0;
if (CAST(NEW.Temperatura AS UNSIGNED)<@tempmin) then
SELECT MAX(idAlarme) into @maxidAlarme FROM alarmes;
SET @maxidAlarme=@maxidAlarme+1;
INSERT INTO alarmes(idAlarme,descricao_alarme, idRegisto) VALUES (@maxidAlarme,"inserted below the normal temperature",New.idRegisto);
INSERT INTO sensores_tem_alarmes(idSensor,idAlarme,dataAlarme) VALUES (NEW.idSensor,@maxidAlarme,NOW());
set @comp=+1;
end if;


set @id_sensores_em_alerta=1;
SELECT MAX(id_sensores_em_alerta) into @id_sensores_em_alerta FROM sensores_em_alerta;
INSERT INTO sensores_em_alerta(id_sensores_em_alerta, idSensor, idAlarme, data_registo, numerosensoresdisparados) VALUES (id_sensores_em_alerta,NEW.idSensor, @maxidAlarme, NOW(), @comp);
end $$;

DELIMITER ;
<小时/>

我尝试在 SQL Server 中创建触发器,但由于脚本不同,我在以正确的方式进行操作时遇到了很多困难。

我的尝试一点也不顺利:

CREATE TRIGGER Alert ON registos AFTER INSERT AS
BEGIN

DECLARE @comp decimal= 0
DECLARE @tempmax decimal= 0
DECLARE @tempmin decimal= 0


DECLARE @current_max_idAlarme int = (SELECT MAX(IdAlarme) FROM alarmes)

-- Insert into alarmes from the inserted rows if temperature less than tempmin
INSERT alarmes (IdAlarme, descricao_alarme, idRegisto)
SELECT
ROW_NUMBER() OVER (ORDER BY i.idRegisto) + @current_max_idAlarme,
'temp Error',
i.idRegisto
FROM
inserted AS i
WHERE
i.Temperatura < @tempmin

END

但不要做任何事情。不要在表警报上创建数据:S

请问有谁可以帮帮我吗?我将永远感激不已。

非常问候,谢谢大家。

最佳答案

首先,MSSQL 没有选项 FOR EACH ROW,因此它会将多个插入的行视为一组。因此,您必须将这些值插入到表变量中。

不幸的是,我实际上不太了解 MySQL,但我相信这是一个起点?

CREATE TRIGGER ALERT
ON records
AFTER INSERT
AS
BEGIN
DECLARE @comp INT;
DECLARE @tempmax INT;
DECLARE TABLE @tempmin (tempmin INT);

INSERT INTO @tempmin
SELECT s.lim_inf_temp FROM sensores s WHERE s.idSensor IN (inserted.idSensor);
--rest of the code

关于mysql - 如何将 mysql 触发器转换/迁移到 Sql Server 触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23756864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com