B.B
B.B

Reputation: 101

How to create conditional SQL insert using trigger

I'm new to SQL and working in SQL Server. There is a table called Employee with columns name, ssn, salary etc. I am trying to write a trigger that checks salary is higher than $20000 when inserting rows.

If it's higher, then do insert, else print 'Salary must be higher'. I have done some research but couldn't find solution.

Here is what I'm thinking, but this it is not working for sure.

create trigger lowSalary 
on EMPLOYEE
INSTEAD OF INSERT
AS
BEGIN 
    SET NOCOUNT ON
        INSERT INTO EMPLOYEE

        IF salary < 20000 THEN
            print 'salary must be > 20000'
END

Additionally, I don't really understand this instead of insert. I found someone used this

INSTEAD OF INSERT
AS
BEGIN 
    SET NOCOUNT ON

Upvotes: 0

Views: 205

Answers (1)

Scott Newson
Scott Newson

Reputation: 2835

Building on @Martin Smith's comment:

Have a look at this page on Check Constraints: http://www.w3schools.com/sql/sql_check.asp

In your case, you could create a constraint like:

CONSTRAINT chk_Salary CHECK (salary > 20000)

Upvotes: 1

Related Questions