Insert And Update Trigger On Same Table
Jul 23, 2005
I currently have 2 tables as follows:
CREATE TABLE [CRPDTA].[F55MRKT119]
(
mhan8 int,
mhac02 varchar(5),
mhmot varchar(5),
mhupmj int
)
GO
CREATE TABLE [CRPDTA].[F55MRKT11]
(
mdan8 int,
mdac02 varchar(5),
mdmot varchar(5),
mdmail int,
mdmag int,
mdupmj int
)
What I would like to do is place a trigger on F55MRKT119 which will
insert records to the F55MRKT11 if they do not exist in that table
based on the [mdan8] field. If the record does exist I would like
Update the corresponding record and increment either the [MDMAIL] or
the [MDMAG] based on the inserted [MHMOT]. What I have so far is as
follows:
TRIGGER #1:
CREATE TRIGGER trgIns_Summary ON [CRPDTA].[F55MRKT119]
FOR INSERT
AS
BEGIN
INSERT INTO CRPDTA.F55MRKT11
select INS.MHAN8, INS.MHAC02, INS.MHMOT,
case when INS.MHMOT='MAG' then 0 ELSE 1 end,
case when INS.MHMOT='MAG' then 1 ELSE 0 end,
'0' from INSERTED INS
WHERE ins.mhan8 not in(select mdan8 from crpdta.f55MRKT11)
END
TRIGGER #2:
CREATE TRIGGER trgUpd_Summary ON [CRPDTA].[F55MRKT119]
FOR Update
AS
BEGIN
UPDATE CRPDTA.F55MRKT11
SET MDMAIL= case when INS.MHMOT='MAG' then 0+MDMAIL
when INS.MHMOT<>'MAG' then 1+MDMAIL end,
MDMAG= case when INS.MHMOT='MAG' then 1+MDMAG
when INS.MHMOT<>'MAG' then 0+MDMAG end
from INSERTED INS JOIN CRPDTA.F55MRKT11
on(ins.mhan8=mdan8)
END
For instance if I do the following insert:
INSERT INTO CRPDTA.F55MRKT119
VALUES('212131','VK4','AL4','0')
then
INSERT INTO CRPDTA.F55MRKT119
VALUES('212131','VK4','MAG','0')
This is what I expect in both tables:
[CRPDTA.F55MRKT119] (2 Records)
MHAN8 MHAC02 MHMOT MHUPMJ
------ ------ ----- ------
212131 VK4 AL4 0
212131 VK4 MAG 0
[CRPDTA.F55MRKT11] (1 Record)
MDAN8 MDAC02 MDMOT MDMAIL MDMAG MDUPMJ
----- ------ ----- ------ ----- ------
212131 VK4 AL4 1 1 0
The insert part works fine in that it iserts in both tables with the
correct values. However it seems as if the Update protion is failing
for some reason. WHat I have tried so far is setting the trigger order
for the update to run first and vice-versa, but still no luck. Any
help would be appreciated.
View 1 Replies
ADVERTISEMENT
Feb 15, 2008
Hello
I've to write an trigger for the following action
When a entry is done in the table Adoscat79 having in the index field Statut_tiers the valeur 1 and a date in data_cloture for a customer xyz
all the entries in the same table where the no_tiers is the same as the one entered (many entriers) should have those both field updated
statut_tiers to 1
and date_cloture to the same date as entered
the same action has to be done when an update is done and the valeur is set to 1 for the statut_tiers and a date entered in the field date_clture
thank you for your help
I've never done a trigger before
View 14 Replies
View Related
Mar 11, 2004
I am new to triggers and need help on the following:
I have a hourly table that inserts new rows every hour but I need to either Insert or Update the daily table with the sum of the reading from the hourly table. If a row exist in the daily table with the date of the hourly table, then I need to update this row but if it doesn't exist, I need to insert this row.
Thanks for any suggestions...
Alan
View 4 Replies
View Related
Jul 23, 2005
Hi,Does anyone know of a simple way to do this? I want to create aninsert trigger for a table and if the record already exists based onsome criteria, I want to update the table with the values that arepassed in via the insert trigger without having to use all the 'set'statements for each field (so if we add fields in the future I won'thave to update the trigger). In other words, I want the trigger codeto look something like this:if exists (select * from TableA where Fld1 = inserted.Fld1) then//don't do insert, do an update instead (would i want to rollback here?and will I have access to the 'inserted' table still?)Update TableASet TableA.<all the fields> = Inserted.<all the fields>where Fld1 = inserted.Fld1end ifAny help or ideas would be appreciated.Thanks,Teresa
View 3 Replies
View Related
May 16, 2006
Hi ,
I have 2 tables (Dept and Emp)
The columns in table Dept are Deptno and Deptname. Deptno is bigint and it is primary key. In Emp table, columns are Empno(PK) ,EmpName and Deptno(foreign key referring to Dept)
To Insert or Update record in Emp through application, value of Deptno is coming as 0(Zero). I want the value of Deptno to be inserted or updated as null if the value is Zero (0). How to do this in sql server 2005 by using trigger on table Emp
Thanks in advance
regards,
Srinivas Govada
View 6 Replies
View Related
Jul 12, 2005
I'm trying to update (increment)
Company.SumtotalLogons
from CompanyUsers.NumberOfLogons
where CompanyUsers.CompanyID = Company.CompanyID
I'd like to either write a formula (if it is even possible to fire a formula from one table update/insert to increment a field in another table), or a stored procedure that triggers an auto update/append into Company.SumTotalLogons
I know this is possible in access, so i'm wondering how to go about it in ms-sql?
any ideas?
View 1 Replies
View Related
Feb 1, 2008
FYI: I'm using SQL2005 on a windows 2003 server.
So, I've written an Instead of Trigger to update a foreign key field based on information in another field of the same record.
To add some error handling to the process I updated the Trigger to insert any records that don't have legitimate foreign keys into a second table.
This process works great when I test it by just adding a record using the table view in the SQL Management Studio or through a query run in the query browser.
However, when a record is added via an ODBC connection I get foreign key constraint errors and records are not added to the second table. If the foreign key is legit the record is added and the part of trigger that updates that keyed field executes just fine.
Is anyone aware of this issue? Is there a way around it?
I found the following MSKB article but I'm not sure if it applies to my situation:
http://support.microsoft.com/kb/304096
Here's my current code, if that track the problem in anyway:
Code:
ALTER TRIGGER UpdateTicketID
ON Email
Instead of INSERT
AS
IF ((Select charindex('{', [subject]) FROM Inserted) = 0)
BEGIN
INSERT INTO
BadEmail ([Subject], Sender, Body, EntryID, LastModificationTime, AttachmentLInk, SendTo, Cc, ContactID)
Select
[Subject], Sender, Body, EntryID, LastModificationTime, AttachmentLink, SendTo, Cc, ContactID
From
Inserted
END
ELSE IF ((Select substring([subject], charindex('{', [subject])+1, (charindex('}', [subject]) - charindex('{', [subject]))-1) From Inserted) NOT In (Select TicketID From Ticket))
BEGIN
INSERT INTO
BadEmail ([Subject], Sender, Body, EntryID, LastModificationTime, AttachmentLInk, SendTo, Cc, ContactID)
Select
[Subject], Sender, Body, EntryID, LastModificationTime, AttachmentLink, SendTo, Cc, ContactID
From
Inserted
END
ELSE
BEGIN
INSERT INTO
Email ([Subject], Sender, Body, ticketID, EntryID, LastModificationTime, AttachmentLink, SendTo, Cc, ContactID)
Select
[Subject]
, Sender
, Body
, substring([subject], charindex('{', [subject])+1, (charindex('}', [subject]) - charindex('{', [subject]))-1)
, EntryID
, LastModificationTime
, AttachmentLink
, SendTo
, Cc
, ContactID
From
Inserted
END
GO
Thank very much for any help.
-Will
View 1 Replies
View Related
Apr 21, 2015
I have a situation where I have Table A, Table B.
View C is created by joining table A and table B.
I have written a instead of trigger D on view C.
I do not insert/update/delete on the view directly.
For every insert/update in table A /B the values should get insert/update in the view respectively. This insert/update on view should invoke the trigger.
And I am unable to see this trigger work on the view if any insert/update occurs on base table level.
Trigger is working only if any operation is done directly on the view.
View 2 Replies
View Related
Jul 20, 2005
Are there any limitations or gotchas to updating the same table whichfired a trigger from within the trigger?Some example code below. Hmmm.... This example seems to be workingfine so it must be something with my specific schema/code. We'reworking on running a SQL trace but if anybody has any input, fireaway.Thanks!create table x(Id int,Account varchar(25),Info int)GOinsert into x values ( 1, 'Smith', 15);insert into x values ( 2, 'SmithX', 25);/* Update trigger tu_x for table x */create trigger tu_xon xfor updateasbegindeclare @TriggerRowCount intset @TriggerRowCount = @@ROWCOUNTif ( @TriggerRowCount = 0 )returnif ( @TriggerRowCount > 1 )beginraiserror( 'tu_x: @@ROWCOUNT[%d] Trigger does not handle @@ROWCOUNT[color=blue]> 1 !', 17, 127, @TriggerRowCount) with seterror, nowait[/color]returnendupdate xsetAccount = left( i.Account, 24) + 'X',Info = i.Infofrom deleted, inserted iwhere x.Account = left( deleted.Account, 24) + 'X'endupdate x set Account = 'Blair', Info = 999 where Account = 'Smith'
View 1 Replies
View Related
Oct 30, 2007
Table 1
First_Name
Middle_Name
Surname
John
Ian
Lennon
Mike
Buffalo
Tyson
Tom
Finney
Jones
Table 2
ID
F
M
S
DOB
1
Athony
Harold
Wilson
24/4/67
2
Margaret
Betty
Thathcer
1/1/1808
3
John
Ian
Lennon
2/2/1979
4
Mike
Buffalo
Tyson
3/4/04
5
Tom
Finney
Jones
1/1/2000
I want to be able to create a trigger that updates table 2 when a row is inserted into table 1. However I€™m not sure how to increment the ID in table 2 or to update only the row that has been inserted.
View 17 Replies
View Related
Feb 5, 2008
A
ID
Name
1
Joe
2
Fred
3
Ian
4
Bill
B
ID
1
4
I want to be able to create a trigger so that when a row is inserted into table A by a specific user then the ID will appear in table B. Is it possible to find out the login id of the user inserting a row?
I believe the trigger should look something like this:
create trigger test_trigger
on a
for insert
as
insert into b(ID)
select i.id
from inserted i
where
--specific USER
View 9 Replies
View Related
Aug 23, 2007
Hi,
Is it possible to group all my update/insert (one table) ?
Cause I hope to have all the update/insert in one Trigger execution. I need to sum up some figures here.
I am using ASP.NET 2.0, SQLOLEDB and SQL 2005.
Please Help and Thank you.
View 8 Replies
View Related
Apr 25, 2002
I would like to update a record in a table when a record is added. The dilema is I want to update the record I am adding. I tried an insert trigger ( it doesn't fail, it just doesn't update) If I use the same syntax in TSQL after the record has been inserted it handles the update properly. SO I think the syntax is OK. I have the trigger below. The question is - Is there a way to do this?
Thanks
CREATE TRIGGER transaction_ins_tr
ON dbo.transactions
FOR INSERT
AS
DECLARE @pat_id varchar(5),
@location_name varchar(50),
@account_id char(12),
@tran_num int
--get patient id
SELECT @pat_id = patient_id
FROM inserted
select @account_id = account_id from dbo.patient pa
where pa.patient_id = @pat_id
--get location
select @location_name = df_sitename from
development..patient_ dp
where dp.account_id = @account_id
-- update trans location
update dbo.transactions
set df_sitename = @location_name
where tran_num = @tran_num
View 1 Replies
View Related
Jan 19, 2004
Tbl1 inserts 1 record(with some fields populated) in tbl2. then I need get values from tbl3 to populate the rest of the fields in tbl2(update the record).
tbl1 = tblallBag_data
tbl2 = tblBag_data
tbl3 = tblShipping_sched
I created a trigger in tbl1 to insert a record into tbl2 and it works fine.
CREATE TRIGGER trgtblBag_Data ON dbo.tbltblallBag_data
FOR INSERT
AS
INSERT INTO tblBag_data (work_ord_num, work_ord_line_num, bag_num, bag_scanned_by, bag_date_scanned, bag_quantity)
SELECT work_ord_num, work_ord_line_num, bag_num, bag_scanned_by, bag_date_scanned, bag_quantity
FROM inserted
How can I update tbl2?
Should I create another trigger to update tbl2?
Should I join the two tbls(tbl2 & tbl3) to find
@work_ord_num = work_ord_num , @work_ord_line_num = work_ord_line_num
Thanks for your help!
View 1 Replies
View Related
Oct 31, 2013
I have several tables that i need to add a trigger to. One such table is "Clusters". This table contains a column called ClusterFKey which should be the same value as the AutoID column in the Serverdata table (same db) and should be populated every time a record is added to the Clusters table. The value should be joined on the servername column's value in both the Serverdata and Clusters table.
So, when a record is added to Clusters, the ClusterFkey should equal the AutoID key in Serverdata where Clusters.servername = Serverdata.server and Clusters.ClusterFkey is null.
View 10 Replies
View Related
Jul 20, 2005
Hi!I wonder how to use conditions in the inserted table(in ainsert/update) trigger? The inserted table contain all the rows thathave been updated or inserted (for an update/insert trigger), but outof all these rows in inserted table, I only want the rows where aparticular field have been updated, for example if idkey have beenupdated it would be in inserted BUT I only want this row if the fieldamount have been updated. Can a use the UPDATE(column) some how? Anyideas?/Jenny
View 2 Replies
View Related
May 2, 2007
I would like to insert an update trigger which should achieve the following functionallity (as per trigger algorithm) but somehow it is not working. can you please help me since I am still green with SQL and programming, but I need to solve this before I can continue!
CREATE TRIGGER ActiveCard
ON AccessControl
FOR Insert (when i insert a new row in Access Control)
AS UPDATE UniqueCard
( to update the matching (match IDNum) row within UniqueCard table)
Set UniqueCard.Active = Inserted.Active (card and active are of the same type)
Where UniqueCard.IDNum = AccessControl.IDNum
Thanks
View 6 Replies
View Related
Nov 24, 2003
I have a table called drugs with a cost, date, and drugname field. I have a history table that I want to insert into anytime the fields are changed in the drugs table. I want to capture the old data along with the new cost. is that possible in a update trigger? What I have below doesn't like when it comes to setting the new cost
create trigger Updt_drugs on drugs for update as
-- updates record with sql user and timestamp
--created 1-12-02 tim cronin
declare @newcost money
begin
set @newcost = select cost from inserted
insert into drugsold ([oldcost],[cost],[cdate],[drug])
select [cost],@newcost,[cdate],[drug]
from deleted dt
end
View 1 Replies
View Related
Aug 15, 2001
I HAVE TWO TABLES IN THE DATABSE AND THE SECOND TALE SI FOR AUDITING.
I WANT CREATE THE TRIGGER ON FIRST TABLE SO THAT I CAN PUT THE STATUS
LIKE INSERT,UPDATE OR DELETE IN THE STATUS COLUMN IN SECOND TABLE.
CAN SOMEBODY HELP IN WRITING THAT TRIGGER..?
HOW CAN I DETERMINE WAETHER THE RECORD IS BEEN INSERTED OR UPDATED OR DELETED.
DO I HAVE TO WRITE A SEPERATE TRIGGER FOR EACH ACTIVITY..OR I CAN WRITE IT IN THE
SINGLE TRIGGER..?
PLEASE SUGGEST ME..ITS URGENT.
THANKS IN ADVANCE
HARISH
View 2 Replies
View Related
Jul 20, 2004
I have a parent table with 27 Columns and Child Table with 37 colums - when even there is an update in any of the columns on Parent or Child table, I require new record inserted into Audit_Parent and Audit_child table. Please help with
SQL Code on Create Trigger and insert records into Audit_parent and Audit_child when an Update occurs on any of the columns.
Insert into AuditParent and AuditChild should occur whenever there is an update on either Parent or child table.
Thanks
:confused:
View 1 Replies
View Related
Jul 11, 2014
I currently have a AFTER UPDATE trigger that looks at a specific column being updated. It works great, but I am now needing to also capture the field data when it is initially created as well. Do I need to build a sperate FOR INSERT trigger to capture the initial column data when inserted, or is it possible to build it into my current AFTER UPDATE trigger?
Here is my current trigger:
CREATE TRIGGER [dbo].[xResponsible_By] ON [dbo].[PARTS_REQUESTOR]
AFTER UPDATE
[code]....
View 2 Replies
View Related
Dec 2, 2014
I have to create a trigger that will log who changed information on a table and when (NOT what they have changed).
My idea is to get the users name and see if it is in a table if not create it and get the associated ID, also get the ID of table that was accessed along with the ID of the type of task that was performed. Take this data and insert it into a table.
Here is the SQL I have so far.
-- Primary Database Tables --
CREATE TABLE Physician (
Physician_ID int not null identity(1,1) primary key,
First_Name varchar(100),
Last_Name varchar(100),
Mobile_Number varchar(15),
Pager_Number varchar(15)
[code].....
View 1 Replies
View Related
Jul 20, 2005
How would I write a trigger that updates the values of a Descriptioncolumn to upper case for even IDs and to lower case for odd IDs? Ineed this trigger to fire for INSERT and UPDATE events.
View 2 Replies
View Related
Mar 8, 1999
In recent testing, I have found that the trigger function UPDATE under SQL Server 6.5 SP5 behaves differently then SP4. For insert, the update function returns true on items that have not been explicitly inserted.
Is this a bug? Is this a new feature change? Where can I get more information on a bug list for SP5?
View 4 Replies
View Related
May 15, 2014
I am currently in the process of writing an INSERT/UPDATE trigger in SQL 2012, the scenario is, I have a table called Quote, what I want to happen is when a record gets added to the table with a field called Approved, populated with a value or a record gets Updated and the Approved field gets populated I want the trigger to execute a stored procedure, passing through a value from a field called Account within the Quote table as a variable. I know I can achieve the action using one trigger "AFTER INSERT, UPDATE" but I am struggling on forming the rest of the trigger.
View 1 Replies
View Related
Feb 20, 2008
Hi,
I'm taking an Excel spreadsheet (that could have around 30k rows) and processing it in SSIS. I essentially have a flag in one of the spreadsheet cols that indicates whether the record is already in the database or not.
I'm splitting the data using a conditional split on this column and using a OLE DB Destination (Fast Load) to perform the inserts and a OLE DB Command to fire a stored procedure to perform any updates. Both the OLE DB Destination and the stored procedure are hitting the same table and the two operations could be executing at the same time as they both appear directly after the Conditional Split, so the OLE DB Destination is set NOT to lock the table.
This seemed to work OK until recently. I've just added 2 triggers onto the table in question which I don't want to fire 30,000 times during the import. As the OLE DB Destination is set to use Fast Load, it doesn't fire the triggers - cool. In the update stored procedure it disables the trigger before performing it's update and re-enables the trigger when finished. Currently this does mean that if you only had updates, the trigger could be enables/disabled 30,000 times. That sounds kinda bad, but I don't really know if this carries a large overhead or not?
If, when importing now you have both updates and inserts the whole process locks up. From looking at activity monitor, it seems as though the INSERT gets suspended.
Do I have a fundamental problem with how I've structured the Data Flow or am I just being really stupid in Enabling/Disabling a trigger that many times, which is probably causing the problem?
Thanks in advance.
View 3 Replies
View Related
Sep 24, 2007
Hello,
I have created a job that fill and update a database from a source db with same structure.
INSERT code is made up comparing the pk column in the source and dest db, the missed ones are filled in the destination.
UPDATE: check col by col, if any change value exists, updated is performed with the following statement for any tables in the DB
UPDATE tableADest
SET col1=source.Col1, col2=source.col2, ... coln=source.coln
FROM tableASource source
INNER JOIN tableAdest dest
ON dest.colpk = source.colpk
The main problem is that I cannot identify the row update in the souce db, everytime I have to compare the whole equivalent tables (source and dest db), because there are not timestamp, updated cols or any cols usefuls, to have a subset of data and find any new or upadeted rows.
I tried replication, but it does not work on that db.
So I created a trigger for each table where new insert or updated row must be detected. The PKs are saved on tables.
The problem is that when I run the application it hold-on, when triggers are disabled the application run fine.
How can I use trigger on several tables without affectrunning application?
Thank
View 3 Replies
View Related
Jun 7, 2006
I am new to triggers and surely could use some help.
I can create a trigger to insert related records based on the main tables ID and insert that value into other related tables fine... but...
How do I create a trigger that can insert a record into one table for a columns given value and then insert a record into another table for another given value?
For instance:
New row...
Table1, Column1 (PK) has a value of 101
Table1, Column2 has a value of 'Blue'.
// When a new row is created in Table1 and Column2 has a value of 'Blue'...
I want to insert a new row into Table2 - with Table1 Column1's value.
// Now if Table1, Column2 has a value of 'Red' when the new row was created...
I want to insert a new row into Table3 - with Table1 Column1's value. Not Table2
This has to be inserted into one or the other tables based on column2's value, not both.
Then I want to populate the other related tables (Table4, Table5) with the regular insert statements based on Table1 Column1's value.
This (the conditional part above) has to work with an update to Table1 also.
So if someone came back to that record and changed Column2's value from 'Blue' to 'Red', it would have to delete the appropriate record in Table2 and then insert the new row into Table3 and visa-versa.
Can I do this with one trigger?
Thanks
View 8 Replies
View Related
Jul 8, 2015
I have a table where table row gets updated multiple times(each column will be filled) based on telephone call in data.
Â
Initially, I have implemented after insert trigger on ROW level thinking that the whole row is inserted into table will all column values at a time. But the issue is all columns are values are not filled at once, but observed that while telephone call in data, there are multiple updates to the row (i.e multiple updates in the sense - column data in row is updated step by step),
I thought to implement after update trigger , but when it comes to the performance will be decreased for each and every hit while row update.
I need to implement after update trigger that should be fired on column level instead of Row level to improve the performance?
View 7 Replies
View Related
Feb 10, 2004
I have never used triggers before and I have tried to solve one problem. If I have the column "currency" in a table and want to make sure that the entered value i valid in relation to another table that contains valid currency formats, I did it like this:
---------------------------------
CREATE TRIGGER [trigger_checkCurrency] ON [dbo].[Client]
FOR INSERT, UPDATE
AS
declare @currency as char(50)
declare @country as char(50)
declare cur cursor for SELECT currency, country
FROMinserted
OPEN cur
fetch cur into @currency, @country
WHILE @@FETCH_STATUS = 0
BEGIN
if not exists(select * from listinfoid where listname = 'currency' and listid = @currency)
begin
set @currency = (cast(@currency as varchar (3)) + ' is not a valid currency')
CLOSE cur
DEALLOCATE cur
RAISERROR (@currency,16,-1) with log
return
end
if not exists(select * from listinfoid where listname = 'country' and listid = @country)
begin
set @country = (cast(@country as varchar (3)) + ' is not a valid contry')
CLOSE cur
DEALLOCATE cur
RAISERROR (@country,16,-1) with log
return
end
else
fetch cur into @currency, @country
END
CLOSE cur
DEALLOCATE cur
update Client set currency = UPPER(currency), country = UPPER(country)
---------------------------------
I use a cursor to handle multiple rows in an update query.
(SQL2000-server)
Is there an easier och better way to do this?
I´m a bit unsure of this code.
Thanx!
/Erik
View 2 Replies
View Related
Jul 18, 2014
I would like to change a value after the table updates inserts a new row based on the value of that column
Table Name is: MPanel
Col Names: RID, FPID.
I want to:
If column RID='16'
Then UPDATE FPID='1'
How can I trigger that update? Would this work:???
CREATE TRIGGER dbo.MyTrigLI
ON dbo.MPanel
FOR INSERT, UPDATE
AS
BEGIN
UPDATE [MPanel]
SET
FPID='1'
WHERE (UPDATE(RID='16')
END
View 9 Replies
View Related
Jul 30, 2014
I have an address table, and a log table will only record changes in it. So we wrote a after udpate trigger for it. In our case the trigger only need to record historical changes into the log table. so it only needs to be an after update trigger.The trigger works fine until a day we found out there are same addresses exist in the log table for the same student. so below is what I modified the trigger to. I tested, it seems working OK. Also would like to know do I need to use if not exists statement, or just use in the where not exists like what I did in the following code:
ALTER TRIGGER [dbo].[trg_stuPropertyAddressChangeLog] ON [dbo].[stuPropertyAddress]
FOR UPDATE
AS
DECLARE @rc AS INT ;
[code]....
View 2 Replies
View Related
Apr 11, 2008
How to create trigger to stop the delete , updation and insert in the table of database ....
How can i stopped .......................I want to apply on whole table of database
Pls help me out.
Yaman
View 3 Replies
View Related