SQL Trigger syntax

I have a table and want to create a trigger that sets a field to "Y" on insert.

Table name APSupplier
Field name OnHold

Can anyone help with syntax?
HKFueyAsked:
Who is Participating?
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
if you need a trigger, you will need a primary key on the table. say it's named PK
CREATE TRIGGER after_insert_table1 ON yourtable 
AFTER INSERT  
AS
BEGIN
  UPDATE t 
      set t.OnHold = 'Y'
     FROM yourtable t
   WHERE t.PK in ( SELECT i.PK FROM INSERTED )
          and ( t.OnHold IS NULL OR t.OnHold <> 'Y' )
 END 

Open in new window

0
 
Lee SavidgeCommented:
Assuming the field is in the table that the trigger is on just set a default value on the field
0
 
Lee SavidgeCommented:
Sorry, posted a bit too early there. To set a default value on a field in a table.

ALTER TABLE APSupplier
ALTER COLUMN OnHold SET DEFAULT 'Y'

Open in new window


This will set the field value to Y for every new record inserted.
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
note: the default will ONLY work if the value is not explicitly set to some value during the insert ...
so, if you want to actually override in such cases, to make sure you have 100% on insert => Y in that field, you indeed need a trigger. otherwise, the above is just fine and more efficient
0
 
HKFueyAuthor Commented:
Thanks Guy, that is spot on!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.