sql server - Creating Trigger for Insert row and Delete row -
i attempting create trigger if row inserted , if row deleted. if row inserted print statement give 1 message, , if row deleted print statement give message. teacher used example, ddl statements instead of dml statements put in. question how can obtain equivalent, making dml statements can work? far output says else print statement whether row inserted or deleted. don't beleive counts insert statement @ all.
here schema.
create table dbo.customers ( customerid int not null identity primary key, customerfname varchar(30) not null, customerlname varchar(30) not null, customeraddress1 varchar(50) not null, customeraddress2 varchar(50) null, customercity varchar(50) not null, customerstate char(2) not null, customerzipcode int not null, customerhome varchar(20) not null, customercell varchar(20) not null, customeremail varchar(50) null );
this data had.
customerid customerfname customerlname customeraddress1 customeraddress2 customercity customerstate customerzipcode customerhome customercell customeremail 1 jane swanson 123 negley ave apartment #3 pittsburgh pa 15222 (412) 555 - 6678 (412) 555 - 6789 jane.swanson@gmail.com 2 phillip connely 167 warble st null pittsburgh pa 15212 (412) 555 - 9463 (412) 555 - 6797 philli123@yahoo.com 3 alfred mansley 41 wild place apartment #4 pittsburgh pa 15205 (412) 555 - 9371 (412) 555 - 4259 mansleyman592@gmail.com 4 angel smith 2050 morningside ave null pittsburgh pa 15222 (412) 555 - 6931 (412) 555 - 1135 angie.smith01@hotmail.com 5 walter weezley 2670 butler st null pittsburgh pa 15210 (412) 567 - 6931 (412) 666 - 1256 walt.disney2012@gmail.com
trigger creation
create trigger table_update on customers after insert, delete if exists (select 1 inserted) print 'the company has gained customers.' else print 'the company has lost customers.'
test
insert customers values('pter', 'jackson', '1240 wlnut st', 'apartment #1', 'pittsburgh', 'pa', 15232, '(724) 789 - 1234', '(724) 555 - 8706', 'pete.jack43@yahoo.com'); delete customers customerfname = 'pter';
upon inserting row message:
the company has gained customers.
msg 2601, level 14, state 1, procedure table_update, line 15
cannot insert duplicate key row in object 'dbo.customers' unique index 'ix_customername'. duplicate key value (jackson, pter).
statement has been terminated.
upon deleting right after message:
the company has lost customers.
(1 row(s) affected)
(1 row(s) affected)
(0 row(s) affected)
my desired output add 1 row or delete 1 row. if choose delete non existing row seems have affect above. seems doing creating more 1 row. have unique key on customer name, if customer appears more once error occur. how can output inserting 1 row inserted , not system trying insert same row multiple times?
how using special tables inserted or deleted
if exists (select 1 inserted) print 'the company has gained customers.' else print 'the company has lost customers.'
Comments
Post a Comment