tsql - SQL Server trigger for update inserted row -


i want create trigger this: have 2 tables:

table 1:

  • id - integer - primary key
  • status - integer - values: 1 busy , 0 available

table 2:

  • id - integer - primary key - autogenerated
  • id2 - integer - null or value of id table1
  • status - integer - values: 1 working 0 waiting
  • col1 - irrelevant column 1
  • col2 - irrelevant column 2
  • col3 - irrelevant column 3

and when users this

insert table2 (col1, col2, col3) values (val1, val2, val3); 

the trigger should check table1 , if finds , available id (status = 0) updates inserted row table2.id2 = table1.id , table2.status becomes 1 otherwise table2.id2 remains null , table2.status becomes 0.

now i've tried many ways , error messages.

this latest attempt:

create trigger mytrigger  on table2 after insert  begin     if not exists (select top 1 id                     table1                    status = 0)     begin         update table2         set status = 0         table2.id = inserted.id     end     else      begin         set status = 1         table2.id = inserted.id          set table.id@ = (select top 1 id                           table1                          status = 0)         table2.id = inserted.id     end end 

and errors:

msg 102, level 15, state 1, procedure mytrigger, line 17
incorrect syntax near '='.

line 17: set status = 1

msg 156, level 15, state 1, procedure mytrigger, line 22
incorrect syntax near keyword 'where'.

line 22: table2.id = inserted.id

and if feel generous next thing need create trigger when column deleted table2 sets status of corresponding id in table1 0 (available)

i using sql server 2012

your second statement missing update command:

    set status=1     table2.id= inserted.id     set table.id@ = (select top 1 id                  table1                 status=0)     table2.id= inserted.id 

should be

    update table2 set table2.status=1,            table2.id = (select top 1 id                  table1                 status=0)     join inserted     on table2.id= inserted.id; 

this should fix errors, however, entire trigger refactored bit cleaner, outside of scope of question.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -