views:

32

answers:

3

The first line seems to be correct. The second line was my SQLite code. With code i get an exception about an error near trigger. In VS it says the multipart identifier could not be bound. With SQLite the new stands for the row being insert. So i would like to increase the count of whomever the subscription recipient is. How do i do that with a SQL Server trigger?

CREATE TRIGGER  trig_0  ON  subscription   
 AFTER INSERT  AS  
UPDATE user_data 
   SET msg_count = msg_count + 1 
 WHERE id = new.recipient; 
+7  A: 

There is no magic 'new' in SQL Server. There is a magic INSERTED, and is a table:

CREATE TRIGGER  trig_0  ON  subscription   
 AFTER INSERT  AS  
UPDATE user_data 
   SET msg_count = msg_count + 1 
FROM user_data
JOIN INSERTED ON id = INSERTED.recipient; 
Remus Rusanu
+1 for the corrected code
Pranay Rana
+1  A: 

i think there is inserted and delted tables used by the trigger not new '''

3> CREATE TRIGGER myTriggerINSERT
4> ON Employee
5> FOR INSERT
6> AS
7> DECLARE @ID int, @Name nvarchar(30)
8>
9> SET @ID = (SELECT ID FROM inserted)
10> SET @Name = (SELECT Name FROM inserted)

for more detail : http://www.java2s.com/Code/SQLServer/Trigger/Getvaluefromupdatedinsertedanddeleted.htm

Pranay Rana
This is a very bad coding practice, insert 2 rows in your batch and your trigger blows up, please read http://blogs.lessthandot.com/index.php/DataMgmt/DBProgramming/MSSQLServer/best-practice-coding-sql-server-triggers
SQLMenace
this is just example to show that there is inserted table used by sql trigger not new
Pranay Rana
A: 

assuming subscription has the column recipient which you can join with user_data.id, here is one way, you can use the inserted pseudo table to join back

CREATE TRIGGER  trig_0  ON  subscription   
 AFTER INSERT  AS  
UPDATE user_data 
   SET msg_count = msg_count + 1 
 WHERE exists (Select * from inserted i where user_data.id = inserted.recipient) 
SQLMenace