Inserted/Deleted Trigger Tables In SP

Mar 29, 2001

SQL 7 SP2

Are the tables inserted and deleted available from within a sp which is called from a trigger ?

Craig

View 1 Replies


ADVERTISEMENT

Problem With My Trigger(inserted/deleted-tables)

Nov 9, 2007



I dont know what I am doing wrong. The trigger (see below) is doing what I want it to do when I do this:


INSERT INTO dbo.personal

(personal_id, chef_id,fornamn, efternamn)

VALUES

(40, 100, 'Malin', 'Markusson' , 'Boss')



but when I remove one value, the result in the logtable is NULL:



INSERT INTO dbo.personal
(personal_id, chef_id,fornamn, efternamn)

VALUES

(40, 100, 'Malin', 'Markusson' )

How can I change the trigger so that it will give me the information of the values that have been updated, inserted or deleted when I dontchange all values (just a couple of them)?


My trigger:
CREATE Trigger trigex

ON dbo.personal

FOR insert, update,delete

AS

INSERT INTO logtable (Innan_värde, Ny_värde)

SELECT

rtrim(cast(d.personal_id as varchar)+', '+cast(d.chef_id as varchar)+', '+rtrim(d.efternamn)+', '+ rtrim(d.fornamn)+ ', '+ rtrim(d.titel)),

(cast(i.personal_id as varchar)+', '+cast(i.chef_id as varchar)+', '+rtrim(i.efternamn)+', '+ rtrim(i.fornamn)+ ' '+ rtrim(i.titel))

FROM inserted i full join deleted d on i.personal_id = d.personal_id


My table:
CREATE Table logtable

(Innan_värde varbinary(max),

Ny_värde varbinary(max))






Thank you !

View 1 Replies View Related

Order Of Records In The INSERTED/DELETED Tables In A Trigger

Nov 29, 2007

We have an app that uses triggers for auditing. Is there a way to know the order that the records were inserted or deleted? Or maybe a clearer question is.... Can the trigger figure out if it was invoked for a transaction that "inserted and then deleted" a record versus "deleted and then inserted" a record? The order of these is important to our auding.

Thanks!
CB

View 1 Replies View Related

Trigger Inserted/Deleted

Mar 26, 2007

Hello,

Is there an alternative to using FETCH to loop through the Inserted/Delete Tables within a trigger? Does this work?

SELECT * FROM Inserted
BEGIN

if INSERTED.IsActive then ...


END

Would this only see the first record?

Currently I'm doing the following;

AS
DECLARE @JobID INTEGER;
DECLARE @IsActive BIT;
DECLARE Temp CURSOR FOR SELECT JobID, IsActive FROM Inserted;
BEGIN
OPEN Temp;
FETCH NEXT FROM Temp INTO @JobID, @IsActive;
WHILE (@@FETCH_STATUS = 0) BEGIN

if @IsActive then ...

FETCH NEXT FROM Temp INTO @JobID, @IsActive;
END;
CLOSE Temp;
DEALLOCATE Temp;

Is this the best method for looping through the Deleted/Inserted or any other table within a trigger?

Thanks,
Steve

View 4 Replies View Related

Trigger- Get Row Number From Inserted/deleted

Jul 19, 2006

I need to add the row number or record number to the 'inserted' and 'deleted' tables in a trigger.

Among other things, I have tried-

SELECT 1 as rowId, i.* INTO #ins FROM inserted i
if @@ROWCOUNT > 1 --if multiple rows, set row number
begin

SELECT @pkWhere = coalesce(@pkWhere + ' and ', ' where ') + PKF.colName + ' <= i.' + PKF.colName FROM #primaryKeyFields PKF
set @strSQL = 'update #ins set rowId = (Select Count(*) From #ins i' + @pkWhere + ')'

exec (@strSql)

end

-the above sets rowId for every record to the total instead of sequential. Keep in mind that this code is used to create a trigger for any table, hence I cannot specify any column names literally.

This SHOULD be simple... right?

View 17 Replies View Related

How Is It Possible That Inserted And Deleted Are Both Empty In Trigger?

Oct 30, 2006

I created manage update trigger to react on one column changes. There is an application which is working with DB, so I don't have access to SQL query which changes this column. In most cases trigger works fine, but in one case when this column changes, trigger is fired and IsUpdatedColumn is true for this column, but both inserted and deleted table are empty, so I can't get new value for this column. Any idea why is it happened? Is any way around?

This column type is uniqueidentifier. Inserted and deleted tables are empty when application is changing value from NULL to not null value, but if I change it myself from Management Studio inserted table contains right values. Most like problem is in query which is changing that value.

I'm doing that on Sql Server 2005.

View 1 Replies View Related

Trigger Problem, Comparing Deleted/inserted Not Working :(

Sep 14, 2007

Hello all,

I have I trigger where I want to insert all _changed_ rows from the INSERTED table into
a table called tempProducts.

If I put this query inside my trigger, I selects exactly the rows I want: rows changed




Code SnippetSELECT * FROM INSERTED
EXCEPT SELECT * FROM DELETED




I the current trigger I have




Code SnippetINSERT INTO dbo.TempProducts (LBTyp, CountryOfOrigin)
SELECT LBTyp, CountryOfOrigin
FROM INSERTED




but this inserts ALL updated rows, not only the changed ones.

So I thought hey, I´ll just combine the two querys and the problem will be solved, like so:



Code Snippet

INSERT INTO dbo.TempProducts (LBTyp, CountryOfOrigin)
SELECT LBTyp, CountryOfOrigin
FROM (SELECT * FROM INSERTED
EXCEPT SELECT * FROM DELETED) as Temp




But for some reason, this won´t work! Why is this? What am I doing wrong?

View 10 Replies View Related

Can I Debug/watch On The Trigger's INSERTED And DELETED Records/values?

Jan 25, 2006

When i debug a trigger is it possible to add a WATCHon the INSERTED or DELETED?I think not, at least I couldn't figure out a way to do so.Does someone have a suggestion on how I can see the values?I did try to do something likeINSERT INTO TABLE1(NAME)SELECT NAME FROM INSERTEDbut this didn't work. When the trigger completed and Iwent to see the TABLE1, there were no records in it.Are there any documents, web links that describe waysof debugging the trigger's INSERTED and DELETED?Thank you

View 11 Replies View Related

Triggers-Inserted/Deleted Tables

Mar 22, 2000

I am reading the WROX "Professional SQL Server 7 Programming" book.
The following code appears on page 424:

CREATE TRIGGER ProductIsRationed
ON Products
FOR UPDATE
AS
IF EXISTS
(
SELECT 'True'
FROM Inserted i
JOIN Deleted d
ON i.ProductID = d.ProductID
WHERE (d.UnitsInStock - i.UnitsInStock) > d.UnitsInStock / 2
AND d.UnitsInStock - i.UnitsInStock > 0
)
BEGIN
RAISERROR('Cannot reduce stock by more than 50%% at once.',16,1)
ROLLBACK TRAN
END

The trigger fires when an UPDATE is made to Products table. The author states that the Inserted and Deleted tables only exist for the life of the trigger, not before, and not after the trigger runs. If this is true, then why would there be any rows in the Deleted table in this case? No rows were
deleted within the trigger. As far as I can see, no rows have been updated
either. If the condition does exist, no rows will be updated, and an error will be displayed. Otherwise, the row will be updated. Then there would be a row in the inserted table. But then the trigger is finished and the inserted table for that trigger disappears. I think my logic is flawed, which is why I am writing. I don't think I fully understand the Inserted and Deleted tables.

Any help would be greatly appreciated.
Nathan

View 7 Replies View Related

Inserted And Deleted Temp Tables ??

Feb 25, 2004

I want to know how inserted and deleted temp tables in SQL server work. My question is more regarding how they work when multiple users accessing the same database. Suppose two users update the database at the same time. In that case what are the values stored in the inserted and deleted tables.

I have a trigger that records changes to the database as in an audit trail. Like any other audit trail I insert data into my audit table from the inserted and deleted temp tables in MS SQL Server. I however am not clear as to how these inserted and deleted tables store values when two users update the database at the same time. Are there separate inserted and deleted tables for each session. The users access the database thru ASP pages.

The audit trail I am trying to use is http://www.nigelrivett.net/AuditTrailTrigger.html

I actually would like to store the inserted and deleted temp tables into other temporary tables so that I can access these tables thru a stored procedure. This is when the problem of same users updating the temporary tables is more pronounced.

Thanks in advance.

View 1 Replies View Related

Relationship Between Inserted And Deleted Tables?

Jul 30, 2007

Hi all,

I just ran across an issue on a SQL 2000 sp4 db where RI was being maintained solely with triggers. I am attempting to change the primary key of a parent table and cascade the results to all its children without using the vendor-supplied trigger code (long story...) using an INSTEAD OF trigger.

My question is: does SQL Server create any kind of relationship between the inserted and deleted tables that I could exploit since the key field is unavailable?

I am trying to avoid having to add a surrogate key to each of the children just for this activity (as there are many M rows in each and no other suitable unique column combinations that span all the child tables).

-DC


View 5 Replies View Related

DML Triggers - INSERTED &&amp; DELETED Tables

Dec 18, 2007



I'm know the above tables are system generated, am I right in assuming the following.

1) The tables are unique to the current user.

2) The tables only last as long as the transaction that caused their creation

Thanks in advance

Alex

View 1 Replies View Related

Table Scan On Inserted And Deleted Tables?

Apr 30, 2001

Hello,

I have a stored procedure that's running a little slower than I would like. I've executed the stored proc in QA and looked at the execution plan and it looks like the problem is in a trigger on one of the updated tables. The update on this table is affecting one row (I've specified the entire unique primary key, so I know this to be the case). Within my trigger there is some code to save an audit trail of the data. One of these statements does an update of the history table based on the inserted and deleted tables. For some reason this is taking 11.89% of the batch cost (MUCH more than any other statement) and within this statement 50% of the cost is for a table scan on inserted and 50% is for a table scan on deleted. These pseudo-tables should only contain one record each though.

Any ideas why this would be causing such a problem? I've included a simplified version of the update below. The "or" statements actually continue for all columns in the table. The same trigger template is used for all tables in the database and none of the others seem to exhibit this behavior as far as I can tell.

Thanks for any help!
-Tom.

UPDATE H_MyTable
SET HIST_END_DT = @tran_date
FROM H_MyTable his
INNER JOIN deleted del ON (his.PrimaryKey1 = del.PrimaryKey1) and
(his.PrimaryKey2 = del.PrimaryKey2)
INNER JOIN inserted ins ON (his.PrimaryKey1 = ins.PrimaryKey1) and
(his.PrimaryKey2 = ins.PrimaryKey2)
WHERE (his.HIST_END_DT is null)
and ((IsNull(del.PrimaryKey1, -918273645) <>
IsNull(ins.PrimaryKey1, -918273645)) or
(IsNull(del.PrimaryKey2, -918273645) <>
IsNull(ins.PrimaryKey2, -918273645)) or
(IsNull(del.Column3, -918273645) <>
IsNull(ins.Column3, -918273645)))

View 1 Replies View Related

Triggers - How Do You Join INSERTED Vs DELETED Tables?

Sep 11, 2001

I want to compare the before and after values of an UPDATEd column using a trigger. I want to know if the value in the column has changed. Simple? No!

As you know, SqlServer puts the before image of the UPDATEd rows into the DELETED virtual table and the after image of the UPDATEd rows in the INSERTED virtual table.

So you would get the before and after data by doing a SELECT on these tables.
But here is the problem - how do you join the tables? What if there are >1 rows in these 2 tables (because the UPDATE affected >1 rows) - how do i know which "old"/DELETED rows correspond to which "new"/INSERTED?"
Ok - I could join the 2 tables on the primary key, but what if the primary key was updated? In that case the join would not work - the DELETED table would contain the old primary key value and the INSERTED table would contain the new (different) primary key value. In fact, ALL of the columns may have been changed by the UPDATE.

Now, there is another thing to try with triggers - the
IF UPDATE ( <columname> )
test. This is designed to tell you if a specified column was UPDATEd by the last UPDATE. However, this will return TRUE for any UPDATE that mentions the column - even if the UPDATE does not change any data! So I cannot determine whether a certain column has had its value changed with this either.

So then you can try another test mentioned in the docs for CREATE TRIGGER - the
IF COLUMNS_UPDATED()
test. However, this will report that a column has been updated, NOT whether the data has changed as aresult of that UPDATE.
So if you UPDATE the value in the column to the same value as it was beforehand (admittedly, a pointless thing to do, but it could happen in some apps), this fuction will say, yes, this column was updated.

So my question remains - how do I know if the data has changed in a column after an UPDATE, using a trigger?
Any ideas?

View 1 Replies View Related

What Is The User Of Inserted And Deleted Tables In Sql Server 2005

Mar 26, 2008

can anybody tell me with an example how to use Inserted and Deleted in Sql Server 2005

View 7 Replies View Related

Order Of Rows In The Inserted And Deleted Psuedo Tables

Aug 15, 2007

I have a table that sometimes has modifications to column(s) comprising the primary key [usually "end_date"]. I need to audit changes on this table, and naturally, turned to after triggers.

The problem is that for updates, when the primary key composition changes, I'm not able to relate/join using the primary key - obviously, it no longer matches across INSERTED and DELETED. Now, for a single row update, it's easy to check for updates on PK columns and then deduce what changes were made...

So the real question is: are rows in INSERTED and DELETED always in matching order (1st row in INSERTED corresponds to the 1st row in DELETED...)?



I don't want to put a surrogate key (GUID nor IDENTITY) on the base table if at all possible. INSERT... SELECT from the inserted/deleted tables into a temp table with identity column is fine, and is what I'm currently doing; I would like MVP or product engineer level confirmation that my ordering assumption is correct.

Testing using an identity surrogate key on base table, and selecting from the Ins/del tables, and the temp tables without an order by clause seems to always return in proper order (proper for my purposes). I've tested under SQL 2005 RTM, SP1, SP2, and SP2 "3152".

FYI, I've lost the debate that such auditing is better handled by the application, not the database server...

Aside: why doesn't the ROW_NUMBER() function allow an empty OVER( ORDER BY() ) clause? Will SQL ever expose an internal row_id, at least in the pseudo tables, so we can work around this situation?

Thanks
Mike

View 12 Replies View Related

Using Inserted / Deleted Tables With Text / NText / Image Data Type

Oct 6, 2004

Hi folks,

Table:

a int,
b int,
c int,
d text

I need to change my AFTER - Trigger from this (example!):

select * into #ins from inserted

to something like

select *(without Text / nText / image -columns) into #ins from inserted.

So I tried to build a string like this: (using INFORMATIONSCHEMES)

select @sql = 'select a,b,c into #ins from inserted'
exec(@sql)

a,b,c are not of Text, nText or Image datatype.

After executing the trigger, I get an error, that inserted is unknown.

Does anyone know how to solve this ?

Thx.

View 5 Replies View Related

Transact SQL :: Triggers - Pass INSERTED / DELETED Logical Tables To Function To Encapsulate Logic?

Jun 13, 2015

I would like to wrap the following code in a function and reuse it.  I use this code in many triggers.

DECLARE @Action as char(1);
SET @Action = (CASE WHEN EXISTS(SELECT * FROM INSERTED) AND EXISTS(SELECT * FROM DELETED)
THEN 'U'  -- Set Action to Updated.
WHEN EXISTS(SELECT * FROM INSERTED)
THEN 'I'  -- Set Action to Insert.
WHEN EXISTS(SELECT * FROM DELETED)
THEN 'D'  -- Set Action to Deleted.
ELSE NULL -- Skip. It may have been a "failed delete".   
END)

Is it possible to write a function and pass the INSERTED and DELETED logical tables to it?

View 5 Replies View Related

Inserted/deleted Table.

Mar 4, 2004

Hi,

I am currently working on a MS SQL server 2000.

I would like to access the data inserted or deleted within a trigger. however the built-in tables -- inserted and deleted --- are not accessible. anyone knows why? And is there any other way to do this?

Thanks

View 1 Replies View Related

Last Inserted, Updated Or Deleted?

Mar 14, 2008

How can we capture the last inserted, updated or deleted ID from the database ?

View 4 Replies View Related

Inserted And Deleted Table

Aug 24, 2007



hi
for after trigger the records stored in followig table
inserted and deleted table.

but i want to know where this tables physically stored ...i mean in which database master or some other database?

and 2nd thing tigger fired for each row or for only insert,delete,update statement?

thanx

View 8 Replies View Related

Log Of Rows Inserted/updated/deleted

Apr 30, 2006

HI, I am wondering if it is possible to retreive this information without using row count transform. Can I get the # of rows inserted/updated or deleted by destination from the log?

Thank you,
Ccote

View 1 Replies View Related

How To Solve Tables Or Functions 'inserted' And 'inserted' Have The Same Exposed Names.

Jul 23, 2005

Hi all!In a insert-trigger I have two joins on the table named inserted.Obviously this construction gives a name collition beetween the twojoins (since both joins starts from the same table)Ofcourse I thougt the usingbla JOIN bla ON bla bla bla AS a_different_name would work, but itdoes not. Is there a nice solution to this problem?Any help appriciated

View 1 Replies View Related

Improving Access To Inserted And Deleted Table

Feb 4, 2008

Is there a configuration or a trick to improve the speed of the access to inserted and deleted tables whithin a trigger? Whenever a trigger is called, the access to inserted or deleted constitute approximatly 95% of the execution time.

Is there a way to have access to inserted and to deleted improved other than copying the data to another table?

View 3 Replies View Related

SQL 2012 :: Replicated Database Log File Grows Exponentially With Few Row Deleted / Inserted

Jun 29, 2015

I have a publisher database set up for a merge replication. This is using parameterized filter with join filters.

I also have a stored procedure that does deletes & inserts on the table where the parameterized filter is applied to aid in changing a subscriber's eligibility to receive so and so data. I have observed that running the stored procedure takes extraordinarily long and as a result, the log file grows to a size 1.5 - 2.5 times the database size.

At first I reasoned that this might because I had it set up to use precomputed partitions and changing it requires recalculating the partitions. As a test, I turned off the precomputed partitions. Didn't work. I turned on "optimize synchronization" AKA "keep_partition_changes", which normally is not available when you have precomputed partition on, and that didn't work, either.

At this point, I think I can rule out precomputed partitions being a problem here but I'm stumped now what else I should do to reduce the amount of log writes being required. We do need the parameterized filters & join tables, so that can't go.

View 0 Replies View Related

How To Correctly Update A Table Which Values Can Be Either Inserted/updated/deleted On Update?

Feb 16, 2006

Hi SQL fans,I realized that I often encounter the same situation in a relationdatabase context, where I really don't know what to do. Here is anexample, where I have 2 tables as follow:__________________________________________ | PortfolioTitle|| Portfolio |+----------------------------------------++-----------------------------+ | tfolio_id (int)|| folio_id (int) |<<-PK----FK--| tfolio_idfolio (int)|| folio_name (varchar) | | tfolio_idtitle (int)|--FK----PK->>[ Titles]+-----------------------------+ | tfolio_weight(decimal(6,5)) |+-----------------------------------------+Note that I also have a "Titles" tables (hence the tfolio_idtitlelink).My problem is : When I update a portfolio, I must update all theassociated titles in it. That means that titles can be either removedfrom the portfolio (a folio does not support the title anymore), addedto it (a new title is supported by the folio) or simply updated (atitle stays in the portfolio, but has its weight changed)For example, if the portfolio #2 would contain :[ PortfolioTitle ]id | idFolio | idTitre | poids1 2 1 102 2 2 203 2 3 30and I must update the PortfolioTitle based on these values :idFolio | idTitre | poids2 2 202 3 352 4 40then I should1 ) remove the title #1 from the folio by deleting its entry in thePortfolioTitle table2 ) update the title #2 (weight from 30 to 35)3 ) add the title #4 to the folioFor now, the only way I've found to do this is delete all the entriesof the related folio (e.g.: DELETE TitrePortefeuille WHERE idFolio =2), and then insert new values for each entry based on the new givenvalues.Is there a way to better manage this by detecting which value has to beinserted/updated/deleted?And this applies to many situation :(If you need other examples, I can give you.thanks a lot!ibiza

View 8 Replies View Related

Getting Inserted Data In Trigger

Feb 22, 2007

I am using SQL Server 2000.I want to create an after insert trigger on one of my tables, but I have forgotten how I reference the inserted data to do some business logic on it. Can someone please help. Thanks Jag 

View 1 Replies View Related

Inserted Row Deletes After Trigger

Oct 22, 2007

I'm hoping someone has seen this before because I have no idea what could be causing it.
 I have an SQL 2005 database with multiple tables and several triggers on the various tables all set to run after insert and update.
My program inserts a record into the "items" via a SP that returns the index of the newly added row. The program then inserts a row into another table that is related to items. When the row is inserted into the second table it gets an error that it cannot insert the record because of a foreign key restraint. Checking the items table shows the record that was just inserted in there is now deleted.
The items record is only deleted when I have my trigger on that table enabled. Here is the text of the trigger:
GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER TRIGGER [dbo].[TestTrigger]ON [dbo].[items]AFTER INSERT
AS BEGIN
SET NOCOUNT ON;
     INSERT INTO tblHistory(table_name, record_id, is_insert)     VALUES ('items', 123, 1)
END
tblHistory's field types are (varchar(50), BigInt, bit).
As you can see there is nothing in the trigger to cause the items record to be deleted, so I have no idea what it could be? Anyone ever see this before?
Thanks in advance!

View 7 Replies View Related

Using Inserted Table In Trigger

Feb 17, 2005

hi, i am writing a trigger to log inserts,updates and deletes in a table and would like to also enter the user details ie who did the transaction. is the spid in the inserted table? if not how do i get this information?

TIA

View 3 Replies View Related

Trigger: Need To Use Inserted In Sp_executesql

Jul 21, 2005

i have a trigger, so need to use the "inserted" table that comes in.

however, i need to use this "inserted" in the following way:


EXEC @LRES = sp_executesql N'
INSERT INTO newtable (col1,col2)
select * from (select acol1,acol2 from inserted WITH (NOLOCK))

however i keep on getting the error that he doesn't know the object "inserted".... I i have the feeling that i may not use inserted at that stage.

what now?

i really need to use the sp_executesql result in the @LRES since after it we should perform some actions in other tables, depending on the result of the @LRES. anyway i really hope anyone can help me as soon as possible.

View 4 Replies View Related

Put Inserted Value Into A Parameter In A Trigger

Sep 6, 2004

How would i get the value of a field that i just inserted and put that into a parameter, so that i could update another table.

This is the code that i used in the trigger that did not work:
@field1 = select srcfield1 from inserted

Anyway here is the full code:

CREATE TABLE Source (srcID int IDENTITY, srcField1 nvarchar(50))
CREATE TABLE Destination (destID int IDENTITY, destField1 nvarchar(50))
go

CREATE TRIGGER tr_SourceInsert ON [dbo].[Source]
FOR INSERT
@Field nvarchar(50) output
AS
SELECT @Field1 = SELECT Field1 FROM inserted
UPDATE Destination
SET Field1 = @Field
where destID = '1'
go

INSERT Source(srcfield1) VALUES ('A')
go

View 3 Replies View Related

How Do I Get A Trigger Just To Copy The Inserted Row.

Feb 8, 2005

HI I have a trigger which I want to copy any rows in the MSmerge_history into a archieve table. I am using this trigger:

CREATE TRIGGER History_replication ON
[dbo].[MSmerge_history]
FOR INSERT
AS
INSERT [dbo].[MSmerge_history_archive]
(
agent_id,
runstatus,
start_time,
[time],
duration,
comments,
delivery_time,
delivery_rate,
publisher_insertcount,
publisher_updatecount,
publisher_deletecount,
publisher_conflictcount,
subscriber_insertcount,
subscriber_updatecount,
subscriber_deletecount,
subscriber_conflictcount,
error_id,
[timestamp] ,
updateable_row
)
SELECT
agent_id,
runstatus,
start_time,
[time] ,
duration,
comments,
delivery_time,
delivery_rate,
publisher_insertcount,
publisher_updatecount,
publisher_deletecount,
publisher_conflictcount,
subscriber_insertcount,
subscriber_updatecount,
subscriber_deletecount,
subscriber_conflictcount,
error_id,
[timestamp],



How this copy the entire contence of the table into the archive each time someone insert a row. How do I get it to only insert the row which had triggered the insert? Ed

View 2 Replies View Related

New To Triggers - Deleted Folder Trigger

Jul 4, 2006

Hi

I would like to know how can I write a trigger for a table that lists folders deleted. I have a table called RECORDS which contains folders and would like to know folders that are being deleted.

Thanks...

View 8 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved