Gabriel Mendes
Gabriel Mendes

Reputation: 13

TSQL - Compare two dates [TRIGGER and IF]

I am trying to compare two dates, @DataJogo with @DataEvento and want to check if the play date is later than the date of the event.

The Trigger works only when the insert is valid appears both selects the IF.

CREATE TRIGGER TriValidaData
ON jogo
AFTER INSERT, UPDATE
AS
DECLARE @DataJogo date, @DataEvento date , @IDJogo int, @IDEvento int
SELECT @IDJogo = id_jogo FROM inserted
SELECT @IDEvento = id_evento FROM inserted
SELECT @DataJogo =  data FROM inserted
SELECT @DataEvento = data FROM evento WHERE id_evento = @IDEvento
IF @DataJogo > @DataEvento
    SELECT 'O jogo foi adicionado com sucesso.' AS 'MENSAGEM';
ELSE
    DELETE FROM jogo WHERE id_jogo = @IDJogo;
    SELECT 'A data não é valida. A inserção de dados não foi efectuada com sucesso.' AS 'MENSAGEM';



INSERT INTO jogo VALUES (11,'15:00:00','16:00:00','2018-05-01',3,10,0)
DELETE FROM jogo WHERE id_jogo = 11;

IMAGE 1 IMAGE 2

Thanks for the help.

Upvotes: 1

Views: 282

Answers (2)

Jatin Patel
Jatin Patel

Reputation: 2104

you need to put the ELSE part in BEGIN... END block like this,

IF @DataJogo > @DataEvento BEGIN
    SELECT 'O jogo foi adicionado com sucesso.' AS 'MENSAGEM';
END
ELSE BEGIN
    DELETE FROM jogo WHERE id_jogo = @IDJogo;
    SELECT 'A data não é valida. A inserção de dados não foi efectuada com     sucesso.' AS 'MENSAGEM';
END

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1270513

Don't do this with a trigger. Do this with a check constraint:

alter table TriValidaData add constraint chk_TriValidaData_datas
    check (@DataJogo > @DataEvento);

If you want to do this using triggers, then you should use an "instead of" trigger and only update/insert into the table when the condition is true.

Upvotes: 1

Related Questions