Reputation: 133
I don't know how to use if else in this case. When score > 10, stop insert. Else continue insert as normally. But what is the syntax to do that?
CREATE TRIGGER invalidScore ON dbo.dbo_score
AFTER INSERT
AS
DECLARE @score DECIMAL;
SET @score = (SELECT s.score FROM Inserted s);
IF(@score > 10)
BEGIN
RETURN 'score must be less than 10'
ROLLBACK TRAN
END
ELSE
BEGIN
END
Upvotes: 0
Views: 1355
Reputation: 66
'Else' is an option section you can remove this and use it,but i may like you to consider using check constraints for scenarios like this rather than adding a trigger check on score column
e.g. CREATE TABLE dbo.dbo_score(
Score int CHECK (score < 10)
);
A CHECK constraint is faster, simpler, more portable, needs less code and is less error prone
Upvotes: 0
Reputation: 27202
There are 3 things you need to change for this trigger to work:
else
section - its optional.Inserted
may have multiple rows.Throw
the error rather than using the return
statement so you can handle it in the client. And throw it after rolling back the transaction in progress.Corrected trigger follows:
create trigger invalidScore on dbo.dbo_score
after insert
as
begin
if exists (select 1 from Inserted S where S.Score > 10) begin
rollback tran;
throw 51000, 'score must be less than 10', 1;
end
end
Upvotes: 1
Reputation: 13006
First, creating these types of sql
objects should use begin.. end
blocks. Second is,you can ignore the else
statement.
CREATE TRIGGER invalidScore ON dbo.dbo_score
AFTER INSERT
AS
BEGIN
DECLARE @score DECIMAL;
SET @score = (SELECT s.score FROM Inserted s);
IF(@score > 10)
BEGIN
RETURN 'score must be less than 10'
ROLLBACK TRAN
END
END
Upvotes: 1