we're just migrating from mariadb (galera) to MSSQL. One of our applications has a very special behaviour - from time to time (I have not found a pattern, the vendor uses very fancy AI-related stuff which noone can debug :-/) it will block the monitor-user of our loadbalancers because of too many connects, so the loadbalancer is no longer able to get the health state, suspends all services on all servers and the whole service is going down.

So I wrote a trigger which enables this user after he will be disabled. I've already thought about a constraint which prohibits this, but then the application goes nuts if it will disable the user.

Anyway - in mysql this works perfectly for us:

delimiter $$

CREATE TRIGGER f5mon_no_disable AFTER UPDATE ON dpa_web_user
    FOR EACH ROW
    BEGIN
        IF NEW.user_id = '99999999' AND NEW.enabled = 0  THEN
            UPDATE dpa_web_user SET enabled = 1 WHERE user_id = '9999999';
        END IF;
    END$$

delimiter ;

I tried this in T-SQL (if it's important, it is MSSQL 2016)

CREATE TRIGGER f5mon_no_disable ON [dbo].[dpa_web_user]
AFTER UPDATE
AS
BEGIN
    IF ( inserted.[user_id] = '9999999' AND inserted.[enabled] = 0 )
    BEGIN
        UPDATE dpa_web_user SET enabled = 1 WHERE user_id = '9999999';
    END
END

I think it's the if-statement which is totally wrong in more than one way - but I do not have an idea how the syntax is in t-sql.

Thanks in advance for your help.


You can use IF EXISTS but you can't reference column values in inserted without set-based access to inserted:

IF EXISTS (SELECT 1 FROM inserted WHERE [user_id] = '9999999' AND [enabled] = 0)
BEGIN
    UPDATE dpa_web_user SET enabled = 1 WHERE user_id = '9999999';
END

You may want to add AND enabled <> 1 to prevent updating a row for no reason.

You can do this in a single statement though:

UPDATE u
  SET enabled = 1
  FROM dbo.dpa_web_user AS u
  INNER JOIN inserted AS i
  ON u.[user_id] = i.[user_id]
  WHERE u.[user_id] = '9999999'
    AND i.[user_id] = '9999999'
    AND u.enabled <> 1
    AND i.enabled = 0;