Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
Sonu619
Posting Yak Master
202 Posts |
Posted - 2012-08-02 : 13:08:53
|
Hi Guys, I need help. I know i am doing something wrong here. Here is the situation. I created a Trigger on table evertime City field Inserted call this triggerand insert same city in different table. When i test and insert one by one Trigger works fine and populate table, However if i tried to Insert four rowstrigger run once and populate only one record insted of four. Below is Trigger. ALTER TRIGGER [dbo].[INSERT_ON_LEFT_TEST] ON [dbo].[LEFT_TEST] FOR INSERTAS BEGIN Declare @City varchar(50) Select @City = city from LEFT_TEST SET NOCOUNT ON; SELECT @CITY = CITY FROM inserted INSERT INTO TRIGGER_TEST (CITY) SELECT @CITYENDPlease help me out where i am wrong. Thank You. |
|
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts |
Posted - 2012-08-02 : 13:14:11
|
The trigger gets called only once per insert, no matter how many rows are inserted. And, a variable can hold only one value - so your @CITY variable is unable to store the data when more than one row is inserted in a single operation. So change your trigger to this: ALTER TRIGGER [dbo].[INSERT_ON_LEFT_TEST]ON [dbo].[LEFT_TEST]FOR INSERTASBEGIN INSERT INTO TRIGGER_TEST ( CITY) SELECT CITY FROM INSERTED;END |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-08-02 : 13:14:53
|
thats because you've written trigger to only process one row at a time so for batch inserts it wont work. so you need to rewrite it asALTER TRIGGER [dbo].[INSERT_ON_LEFT_TEST]ON [dbo].[LEFT_TEST]FOR INSERTAS BEGINSET NOCOUNT ON;INSERT INTO TRIGGER_TEST (CITY)SELECT cityFROM INSERTEDEND ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|