SQL Trigger, связывающий операторы IF - PullRequest
0 голосов
/ 18 октября 2019

Мне кажется, что я не могу иметь несколько несвязанных операторов if в SQL

У меня есть таблица пользователей с несколькими столбцами, которые должны быть уникальными, но некоторые из них также являются необязательными. Поскольку SQL выдает ошибку, когда более одного поля имеют значение NULL, я решил подойти к проблеме с триггером.

Вот как я это написал:

create definer = root@localhost trigger `check-if-unique-update`
    before UPDATE
    on contact
    for each row
    if new.phone2 is null
    then
        if (select count(id) from contact where phone2 = new.phone2 or phone = new.phone2) > 0
        then
            SIGNAL SQLSTATE '45000'
                SET MESSAGE_TEXT = 'There is something wrong with the Contact data you entered!';
        end if;
    end if;

    if new.email2 is not null
        then
        if (select count(id) from contact where email2 = new.email2 or email = new.email2)
            then
            SIGNAL SQLSTATE '45000'
                SET MESSAGE_TEXT = 'There is something wrong with the Contact data you entered!';
        end if;
    end if;

    if new.fax is not null
        then

        end if;
    end if;

Во-первых,DataGrip (IDE управления базой данных от JetBrains) выдает мне ошибку. Когда я затем загружаю файл в базу данных MySql, он показывает только первый оператор if

if new.phone2 is null
    then
        if (select count(id) from contact where phone2 = new.phone2 or phone = new.phone2) > 0
        then
            SIGNAL SQLSTATE '45000'
                SET MESSAGE_TEXT = 'There is something wrong with the Contact data you entered!';
        end if;
    end if;

Мне кажется, что я упускаю некоторые элементарные детали, или это просто невозможно в sql?

1 Ответ

1 голос
/ 18 октября 2019

Вы пытались включить в свой триггер начало-конец?

create definer = root@localhost trigger `check-if-unique-update`
    before UPDATE
    on contact
    for each row
    begin
        if new.phone2 is null
        then
            if (select count(id) from contact where phone2 = new.phone2 or phone = new.phone2) > 0
            then
                SIGNAL SQLSTATE '45000'
                SET MESSAGE_TEXT = 'There is something wrong with the Contact data you entered!';
            end if;
        end if;

        if new.email2 is not null
            then
            if (select count(id) from contact where email2 = new.email2 or email = new.email2)
                then
                SIGNAL SQLSTATE '45000'
                SET MESSAGE_TEXT = 'There is something wrong with the Contact data you entered!';
            end if;
        end if;

        if new.fax is not null
            then

            end if;
        end if;
    end

В зависимости от вашей среды IDE может потребоваться, например, изменить разделитель на //.

Дляссылка см .: https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...