• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 346
  • Last Modified:

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?
0
HKFuey
Asked:
HKFuey
  • 2
  • 2
1 Solution
 
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
 
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
 
HKFueyAuthor Commented:
Thanks Guy, that is spot on!
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now