Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server






SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





Trigger And Update() Function!


In the SQL 7.0 Documentation is indicated that the UPDATE(<fieldname>), if
used in a isert/update trigger, it return TRUE or FALSE based on presence of <field> in the SET List, if the trigger was fired by an UPDATE operation, or in the list of field to fill, if the trigger was fired by an INSERT operation.

Below there is a piece of code that demostrate the false documentation
assertion in the case of a trigger fired by an INSERT operation, infact even
if i have specified only the FIELD1 in INSERT Statement the trigger Print in the screen that i have touched FIELD2 too.

Now the SP1 don't solve this BUG, even if i had read some month ago (before
that SP1 was out) that in SP1 this will be fixed!

Anyone Can Help me to solve this problem, indicating me where i can post the
problem to sensitize the Microsoft's Service Pack Factory ?

Thank in Advance

PS:Sorry for my Bad English .... correct me please if some part are not
readable!

------[Cut Here]-------------------

CREATE TABLE TEST (FIELD1 INTEGER , FIELD2 INTEGER )
GO

CREATE TRIGGER TriggerIU_Test
ON TEST
FOR INSERT, UPDATE
AS

IF UPDATE(FIELD1) PRINT 'Field 1 Touched'

IF UPDATE(FIELD2) PRINT 'Field 2 Touched'
GO

print 'InsertIng '
INSERT INTO TEST (FIELD1) VALUES (2)

print 'Updating '
UPDATE TEST set FIELD1 = 1

GO
DROP TABLE TEST
------[Cut Here]-------------------




View Complete Forum Thread with Replies
Sponsored Links:

Related Messages:
SP5 Problem For Insert Trigger Update Function
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 Replies !   View Related
Trouble With Update Trigger Modifying Table Which Fired Trigger
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 Replies !   View Related
Trigger UPDATEing Another Table With An UPDATE Trigger...
Hi,
Let's say I have Table A & B. I have a trigger for UPDATE and INSERT on table A that updates a field in table B. This works great. I have just realized that I need to keep the field in table B from being updated by anything other than table A's trigger. Still with me... So I added a trigger to table B for INSERT and UPDATE that looks like the following:

IF UPDATE(Quantity)
BEGIN
RAISERROR(50001, 16, -1)
ROLLBACK TRAN
END

The user can change anything in table B except the Quantity field. Is there a way to disable the trigger on table B from firing when the UPDATE is fired from the trigger on table A?

-Alan

View Replies !   View Related
Trigger To Update One Record On Update Of All The Tables Of Database
hi!

I have a big problem. If anyone can help.

I want to retrieve the last update time of database. Whenever any update or delete or insert happend to my database i want to store and retrieve that time.

I know one way is that i have to make a table that will store the datetime field and system trigger / trigger that can update this field record whenever any update insert or deletion occur in database.

But i don't know exactly how to do the coding for this?

Is there any other way to do this?

can DBCC help to retrieve this info?

Please advise me how to do this.

Thanks in advance.

Vaibhav

View Replies !   View Related
Update Function: Why SQL Server Update An Empty String With 0?
I'm new to this forum.
This 'problem' has occured many times, but I've always found a way around it.
I have pages with datagrids, in which a user can edit a certain fields and then update the tables with new data. Lets say when a user edit a Name field and a money field. If he/she left those two fields blank, the table is automatically updated with a <null> (for the name field) and a 0 (for the money field.) Both these columns were set up to allow Null values.
Anyone has an idea why they were updated that way? And is there like a standard on how the data types are updated if a field is left blank?
Thank you very much.

View Replies !   View Related
Update Trigger Behaviour W/o A Trigger.
Hi,
I am not sure if this is the right forum to post this question.
I run an update statement like "Update mytable set status='S' " on the SQL 2005 management Studio.
When I run "select * from mytable" for a few seconds all status = "S". After a few seconds all status turn to "H".
This is a behaviour when you have an update trigger for the table. But I don't see any triggers under this table.
What else would cause the database automatically change my update?
Could there be any other place I should look for an update trigger on this table?
Thanks,
 

View Replies !   View Related
How To Use Update Column For 2 Columns In Update Trigger
I wanted to write a trigger in SQL 2000 checking for an update for 2 columns. If I do one column like "if update(PATIENT_ACPT_STATUS)"
it works fine. If I want to add a second column I tried to
use "if update(PATIENT_ACPT_STATUS,pat_note)" it doesn't like the syntax. BOL says you can use more than one column but does not give an example. Has anyone tried this yet? Thanks

View Replies !   View Related
Trigger To Update A Table On Insert Or Update
 

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 Replies !   View Related
Update Trigger - Update Query
Hi there,I'm a little stuck and would like some helpI need to create an update trigger which will run an update query onanother table.However, What I need to do is update the other table with the changedrecord value from the table which has the trigger.Can someone please show me how this is done please??I can write both queries, but am unsure as to how to get the value ofthe changed record for use in my trigger???Please helpM3ckon*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!

View Replies !   View Related
Update Trigger To Update Another Table
I have an update trigger which fires from a transactiion table to update a parent record in another table. I am getting no errors, but also no update. Any help appreciated (see script below)

create trigger tr_cmsUpdt_meds on dbo.medisp for UPDATE as

if update(pstat)
begin
update med
set REC_FLAG = 2
from deleted dt
where med.uniq_id = dt.uniq_id
and dt.pstat = 2
and dt.spec_flag = 'kop'
end

View Replies !   View Related
INSTEAD OF UPDATE Trigger To Hold Update
 

hi!
 
i have a database with about 20 tables. i appended to each table a column "UpdatedOn", and i want to write a trigger to set the date of the update date in that column, using a trigger.
 
i want to avoid the trigger launching for the last column (UpdatedOn).
 
how can i detect the rows that changed, and modify only the update date/time?
i read something about TableName_Inserted and TableName_Deleted, but i would prefer to copy as generic as possible the data from there, meaning, not to write column names in my script.
 
another idea i thought about was to prevent the trigger executing if no other column except for UpdatedOn changed, but... i encounter some trouble, when i try to pass column name (as string) to UPDATE() function.(Error: Expecting ID or QUOTED_ID)
 
thank you in advance.

View Replies !   View Related
UPDATE Trigger Issue When Using UPDATE
I am trying to update a fields with an UPDATE statement but I keep getting the error message when I run the query.

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

I have this Update trigger that I know is causing the error message because I guess it's not built to manage multi-row updates.

Can someone help me re-write it. I also tried using the WHERE p.ID = p.ID but when I do that it modifies all rows in the modifieddate column instead of just the cells/rows that I'm updating

ALTER TRIGGER [dbo].[MultitrigCA]
ON [dbo].[ProdDesc]
AFTER UPDATE
AS

SET NOCOUNT ON

IF UPDATE (codeabbreviation)
UPDATE p
sET p.ModifiedDate = GETDATE()
FROM ProdDesc AS p
WHERE p.ID = (SELECT ID FROM inserted)

View Replies !   View Related
Calling VB.NET Function From SQL Trigger
 
I have VS 2003 & SQL Server 2005.I have created VB.NET console application which calls various function. Based on data insertion/ updatation in SQL 2005 I need to call function from my VB.NET application. That is from SQL insert/update trigger I need to call function from my console application which is continuouly running.
 

I need help on how can I capture insert trigger event VS 2003 console application?

View Replies !   View Related
Trigger On Table-valued Function?
Is there a way to create a trigger directly on an inline or multi-line tablevalue function?I am trying to create a quick-and-dirty application using an Access DataProject front-end with SQL 2000 SP3 EE.Thanks.

View Replies !   View Related
Calling VB.NET Function From Trigger In SQL 2005
I have VS 2003 & SQL Server 2005.I have created VB.NET console application which calls various function. Based on data insertion/ updatation in SQL 2005 I need to call function from my VB.NET application. That is from SQL insert/update trigger I need to call function from my console application which is continuouly running.
 

I need help on how can I capture insert trigger event VS 2003 console application?

View Replies !   View Related
SQL Server 2005 Query/trigger/function (whatever It Is That I Need)
Hey guys maybe you can help me out, been trying to figure this one out all day at work. I know how to use columns in a table to calculate another column in that same table. But I need to do some math on columns from a totally seperate table. Here is my scenario
 table 1 = stock table
 table 2 = Purchase order table
 in table 2 there are line items that have ordered quantities for parts that we have ordered
 in table 1 under each part number is a field for "quantity on order"
I need to compute the "quantity on order" in table 1 by summing all of the quantities in table 2 where the partnumber = the partnumber from table 1
 
quantity on order (table 1) = sum of all quantities (table 2) where the part numbers match
so for part number 516 i have this
 
table 2
poNumber             partNumber                 quantity
1                             516                             1
2                             516                             12
3                             516                             4
 
table 1
partNumber            inStock              onOrder
516                          0                        17(this is what i am trying to figure out how to compute)
 
any help on this qould be appreciated. I would like the database to automatically do this itself if at all possible.

View Replies !   View Related
Does A Function Trigger A Profiler SP:Complete Event?
I have a stored procedure that uses a returned table form a function as one of its primary datasources.  When I run the query in Analyzer with a trace on Stored Procedure event SP:Complete I get multiple Complete events.  This leads me to beleive that the function completing triggers the event but I am looking for outside confirmation.

We are having problems with traffic on one network segment and the network admin is pointing to these events and saying that my ap is making multiple calls to the procedure, thus causing the traffic problem..

View Replies !   View Related
Maximum Stored Procedure, Function, Trigger, Or Vi
HI ALL,
I AM USING SQL SERVER 2005.
I HAVE RETURN A RECURSIVE FUNCTION TO FIND OUT WHETHER THE NEXT DATE DOES NOT FALL WITHIN HOLIDAYS
BUT I AM GETING THIS ERROR
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).

THE CODE I USED IS


alter FUNCTION [dbo].[GetNextDay](@dt datetime , @empcode varchar(50) )
RETURNS datetime
AS
BEGIN
DECLARE @zoneid VARCHAR(50)
declare @lvlflag varchar(50)
declare @utdt DATETIME
DECLARE @RETDT DATETIME
DECLARE @COMPDT DATETIME


Select @lvlflag= b.ulm_user_field_flag from bbraun_emis.dbo.emp_reference a join bbraun_emis.dbo.user_lvl_master b on b.ulm_user_lvl_id = a.ER_USER_LVL and a.er_emp_code = @empcode
SELECT @zoneid = ZONECODE FROM bbraun_emis.dbo.VWREGIONLINK WHERE CITYCODE IN (SELECT DISTINCT HM_CITY_CODE FROM bbraun_emis.dbo.HOSP_MASTER WHERE HM_HOSP_CODE IN (SELECT HER_HOSP_CODE FROM bbraun_emis.dbo.HOSP_EMP_REL WHERE HER_EMP_CODE in(@EMPCODE)))
select @compdt = holiday_date from oriffconnect.dbo.holiday_master where zone_code = @zoneid and field_staff = @lvlflag and holiday_date = @dt

if(@@ROWCOUNT = 0)
begin

Select @utdt = DATEADD(dd,1,@utdt)
SeT @utdt = ([dbo].[GetNextDay](@utdt , @empcode))
end
IF(@@ROWCOUNT <> 0)
begin
set @utdt = @dt
end
Select @RETDT = @utdt
RETURN @RETDT

END




PLEASE HELP

View Replies !   View Related
Question About Querying Xml Returned By Eventdata() Function In Ddl Trigger
Hi All,
I wanted to query the xml returned by the eventdata() function in a ddl
trigger to view it in result set.
 
I made that code but it returned null, any help please?

create trigger DatabaseEvents
on database
for
ddl_database_level_events
as
--select
eventdata().value('(/EVENT_INSTANCE/EventType/text())[1]','nvarchar(max)')
declare @data xml
select @data = eventdata()
select
Col.value('(/EventType/text())[1]','nvarchar(max)') as 'Event Type'
,Col.value('(/PostTime/text())[1]','datetime') as 'Post
Time'
from
@data.nodes('/EVENT_INSTANCE')
as EventsTable(Col)
go
 
 
Thank you in advance,
Bishoy

View Replies !   View Related
Help Using Update Trigger
Hi
How do i use update trigger...
What I want is that u got "money" and there is a thing you want to buy
You got total 200 money then this thing cost 300 money, and this dont work becouse
200-300 =-100
Now how can i do like it register that its under zero, i know u have to use update trigger...
Please help me,
Thanks.
Even knutli

View Replies !   View Related
Update Trigger
Hello all. I have a table which is the exact replication of a different table. Now if an update takes place in the original table I want to copy that row into the new table without the update.I have this but I am not sure if it works.Create Trigger Content_Archive on content
For Update
As
Insert Into content_audit Select * From DeletedI dont know if Updated exists so I am using Deleted. It is returning both rows (before and after update). And the insert should take place as soon as an update takes place in any field in the content table.

View Replies !   View Related
UPDATE Trigger For PK
i am using address table to store the address of employees, agents, students; so can't use cascade update and delete. so i decided to use trigger but i got stuck here as well.
Here employeeid is the PK of employee id. so when it is updated, i want to update that id in corresponding address table as well.
so what i need is to find out the previous value of EmployeeID before updating to use in WHERE clause and new EmployeeID to use in SET clause.

<code>
CREATE TRIGGER [AddressUpdate] ON [dbo].[MCS_Employee]
FOR UPDATE
AS
IF UPDATE(EmployeeID)
BEGIN
UPDATE MCS_Address SET EmployeeID = 'i am stuck here; how to know the previous value?
WHERE EmployeeID = ???
END
</end>

ironically, PK in my table can be updateable as well.

View Replies !   View Related
Update Trigger
Hello All,
I've been adviced without much detail that the best way to handle updates is with an Update Trigger to write to an AuditTable.
I always thought it was better to avoid triggers.
I'm getting confused very fast in reading about triggers.
Could someone please point me in the right direction?

Thank you,
Tina

View Replies !   View Related
Help With Update Trigger
Hi all,I know squat about triggers so was hoping somebody could point me in theright direction. I wanted to copy an email address field from a salesmantable to a note field in a customer table. Seems easy enough for a one timeupdate. But I would like to add a trigger to auto-update the customer tableanytime an email address changes in the saleman table or a new salesmanrecord is added.Here's my update script (this copies the salesman email address to each ofhis customers)UPDATE CUSTOMERSSET NOTE_5 = SALESMAN.EMAIL_ADDRFROM CUSTOMERS INNER JOINSALESMAN ON CUSTOMERS.SLSPSN_NO = SALESMAN.SLSPSN_NOHow can I turn this into a trigger for automatic updates?Thanks for any help.

View Replies !   View Related
Update Trigger Or ?
Hello,I've a problem where some data gets updated but I don't know whichprocess (SP) is responsible for it (it's an old installation which I'vetaken over).Is it somehow possible to know which process/user/SP performs an updateon a special table/column?I was thinking about to implement an update trigger but unfortunatelyI've no idea how to figure out the "parent process" which wasresponsible for the update.I'm using MS SQL Server 2000.Thanks Joerg

View Replies !   View Related
TRIGGER After UPDATE
Hi there!I need to write a trigger that will check referential integrity of mydata. I have few FOREIGN KEY constraints but, as You probably konow, thecannot be deferred (in the meaning of SQL 92 standard). So I decided toadd NOCHECK CONSTRAINT ALL to the modified table and then run a trigger(after secon altertion of my table). But I cannot write a trigger forALTER. I found something on msdn, byt their example doesn't work. Toshow what's my problem look at this example:CREATE TABLE Indeksy(id_indeksu INT CONSTRAINT indeksy_pkey PRIMARY KEY,numer INT CONSTRAINT wymagany NOT NULLCONSTRAINT unikatowy UNIQUE);CREATE TABLE Studenci(id_studenta INT CONSTRAINT studenci_pkey PRIMARY KEY,indeks INT CONSTRAINT indeks_studenta REFERENCES Indeksy(id_indeksu)ON DELETE CASCADEON UPDATE CASCADE--DEFERRABLE INITIALLY DEFERREDCONSTRAINT tylko_raz UNIQUE,nazwisko VARCHAR(255) CONSTRAINT nazwisko_wymagane NOT NULL);GOCREATE TRIGGER ReferentialIntegrityTriggerForStudenciON DATABASEAFTER ALTERASBEGINDELETE FROM Studenci WHERE Studenci.Indeks NOT IN (SELECT id_indeksuFROM Indeksy);ENDGOENABLE TRIGGER ReferentialIntegrityTriggerForStudenci ON Studenci;GOINSERT INTO Indeksy VALUES (1,1111111);INSERT INTO Indeksy VALUES (2,1211111);INSERT INTO Studenci VALUES (1,1, 'Kowalski');INSERT INTO Studenci VALUES (2,2, 'Nowak');--deferredALTER TABLE StudenciNOCHECK CONSTRAINT ALLINSERT INTO Studenci VALUES (3,5, 'Odraczacz');INSERT INTO Studenci VALUES (4,130, 'Powolny');INSERT INTO Studenci VALUES (5,4, 'Grabowski');INSERT INTO Indeksy VALUES (3,1121111);INSERT INTO Indeksy VALUES (4,1112111);INSERT INTO Indeksy VALUES (5,1111211);ALTER TABLE StudenciCHECK CONSTRAINT ALLWhen I run this script I get a message: Msg 156, Level 15, State 1,Procedure ReferentialIntegrityTriggerForStudenci, Line 4Incorrect syntax near the keyword 'ALTER'.Without it INSERT INTO Studenci VALUES (4,130, 'Powolny'); insertsinvalid data that cannot be checked... Of course this is only an example.Could you, please, write simillar, WORKING :-) trigger for me?Thanx!Wojciech

View Replies !   View Related
Trigger And Row Update Help
I have a table that matches up Securities and Exchanges. Individualsecurities can belong on multiple exchanges. One of the columns, namedPrimaryExchangeFlag, indicates if a particular exchange is the primaryexchange for that symbol. Each symbol can only have one primaryexchange.I am trying to write a insert/update/delete trigger that enforces thisrule. The rules I have thought of are as follows:Insert If new row has flag set, turn off flag for other rows forthat symbol. Otherwise, do nothing.Update If updated row has flag set, turn off flag for other rowsfor that symbol. Otherwise, set flag on first (MAX or MIN or TOP 1???) row for that symbol.Delete If deleted row had flag set, set flag on first row for thatsymbol. Otherwise, do nothing.My basic problem is how to do this when the trigger gets thrown formultiple rows. (Since SQL does not throw individual triggers for eachrow.)Thanks.

View Replies !   View Related
Update Trigger Plz Help
well basically i have a table with 3 columns in a table called TEST like:

TEST1 TEST2 TEST3
------- ------- -------
NULL NULL NULL

these columns can allow nulls. What i whant to do with my trigger is do a after trigger and check after the load if a certain column is NULL place a X instead like a flag but only on the columns that are NULL how would i do this.

plz help

View Replies !   View Related
Update Trigger - Old Value
Is there a way I can get the old value of a specific field when using an update trigger?
e.g. I want to use the condition 'If Update(Column) '
in odrer to create a logfile which stores the old and new value of a field.
The new value can be get from a Select from Inserted table.
Is there a way I can get the old value (before update) also??

Regards,
Manolis

View Replies !   View Related
Update Trigger
I have created a table with the following columns Jobnumber varchar(20), weight real(4), freightcost money(8), trackingnumber vchar(50), comments varchar(2000) and voidid varchar(3)

I wrote a trigger that updates this data based on the voidid to update the package table as followed:
CREATE TIGGER [UPS] ON dbo.UPSSHIPMENT
FOR INSERT
AS
DECLARE @JOBNUMBER CHAR(20)
DECLARE @WEIGHT REAL(4)
DECLARE @FREIGHTCOST MONEY(8)
DECLARE @TRACKINGNUMBER CHAR(25)
DECLARE @SHIPMETHOD CHAR(50)
DECLARE @voidid char(2)



SELECT @JOBNUMBER=JOBNUMBER,
@WEIGHT=WEIGHT,
@FREIGHTCOST=FREIGHTCOST,
@TRACKINGNUMBER=TRACKINGNUMBER,
@SHIPMETHOD=SHIPMETHOD,
@VOIDID=VOIDID
FROM INSERTED



UPDATE PACKAGE
SET PACKAGE.WEIGHT = @WEIGHT,
PACKAGE.FREIGHTCOST = @FREIGHTCOST,
PACKAGE.TRACKINGNUMBER = @TRACKINGNUMBER,
PACKAGE.COMMENTS = @SHIPMETHOD
WHERE PACKAGE.JOBNUMBER = @JOBNUMBER
AND @VOIDID = 'N'



UPDATE PACKAGE
SET PACKAGE.WEIGHT = '',
PACKAGE.TRACKINGNUMBER = '',
PACKAGE.COMMENTS = 'UPS VOID',
PACKAGE.FREIGHTCOST = ''
WHERE PACKAGE.JOBNUMBER = @JOBNUMBER
AND @VOIDID = 'Y'

I am getting the following error see attached.
Any help would be great Thank you!

View Replies !   View Related
Update Trigger
Hallo there,

I'm totally new to writing triggers, but managed to get a trigger to update a specific column (ufINCTcost) on change of another column (ufINCKm)

My problem is that the trigger performs this update on ALL rows, which makes it very slow. How can I get it to only update the column on the row where the change was made ?

My trigger looks as follows:


CREATE TRIGGER updateincidents ON [dbo].[_rtblIncidents]
FOR UPDATE, INSERT
AS
IF UPDATE (ufINCKm)
BEGIN
UPDATE dbo._rtblIncidents
SET ufINCTcost=dbo._rtblIncidents.ufINCKm+dbo._rtblInc idents.ufINCToll+dbo._rtblIncidents.ufINCParking+d bo._rtblIncidents.ufINCFlight+dbo._rtblIncidents.u fINCRental

Hope you can help !!

View Replies !   View Related
Trigger On Update
Hi,

I've got 2 tables, EMPLOYEE and STORE

The EMPLOYEE table holds all the basic stuff you would want to know about an employee and it contains a STORE_CODE attribute that points to the same attribute in the STORE table (to keep track of the store they work at). The STORE table has the STORE_CODE attribute, a NUM_EMP attribute that keeps track of the number of employees at that store, and some other information that is of no relevance to the question.

I've written the following TRIGGER to update the NUM_EMP attribute in STORE everytime a row is inserted or deleted from EMPLOYEE. It works fine for inserts and deletes but I am clueless as how to make it work for updates (an EMPLOYEE transfers to another store). I appreciate any feedback and please feel free to tell where I've gone wrong so far.

Thanks!


CREATE TRIGGER [UPDATENUMEMP] ON [EMPLOYEE]
FOR INSERT,UPDATE,DELETE
AS

DECLARE @STORECODE INT
DECLARE @NUMEMP INT

/*DELETE CASE*/
IF (NOT EXISTS (SELECT * FROM INSERTED) AND EXISTS (SELECT * FROM DELETED))
BEGIN
DECLARE DELETECURSOR CURSOR FOR
SELECTSTORE_CODE, COUNT(*) AS NUMEMP
FROMDELETED
GROUP BY STORE_CODE

OPEN DELETECURSOR

FETCH NEXT FROM DELETECURSOR INTO @STORECODE, @NUMEMP
WHILE(@@FETCH_STATUS = 0)
BEGIN
UPDATESTORE
SETNUM_EMP = NUM_EMP - @NUMEMP
WHERESTORE_CODE = @STORECODE
FETCH NEXT FROM DELETECURSOR INTO @STORECODE, @NUMEMP
END
CLOSE DELETECURSOR
DEALLOCATE DELETECURSOR
END

/*INSERT CASE*/
IF(EXISTS (SELECT * FROM INSERTED) AND NOT EXISTS (SELECT * FROM DELETED))
BEGIN
DECLARE INSERTCURSOR CURSOR FOR
SELECTSTORE_CODE, COUNT(*) AS NUMEMP
FROMINSERTED
GROUP BY STORE_CODE

OPEN INSERTCURSOR

FETCH NEXT FROM INSERTCURSOR INTO @STORECODE, @NUMEMP
WHILE(@@FETCH_STATUS = 0)
BEGIN
UPDATESTORE
SETNUM_EMP = NUM_EMP + @NUMEMP
WHERESTORE_CODE = @STORECODE
FETCH NEXT FROM INSERTCURSOR INTO @STORECODE, @NUMEMP
END
CLOSE INSERTCURSOR
DEALLOCATE INSERTCURSOR
END
GO

View Replies !   View Related
Update Trigger
This is something I have limited experience on. I need to create an update trigger after insert on one table that updates a completely different production table. My development server is being re-done and I'm not sure when it will be back on line. I have created some audit tables using triggers but they a simple inserts into a new table.

I believe the trigger statement should look like this, any advice would be appreciated.

Thanks in advance.

CREATE TRIGGER OB$1InsertAudit ON OB$0001
AFTER INSERT
AS
Begin
Update AX$0001
Set AX$0001.receiveddate=getdate(), AX$0001.docreviewstatus=null where Ob$0001.objid=AX$0001.refobjid and OB$0001.recordtype=6 and
OB$0001.descriptor in('Ancillary Services Tracking Form',
'FCE Referral Request',
'Remain At Work',
'Voc Rehab Job Retention')

End

View Replies !   View Related
Update Trigger
Hi,

If I have a situation where a particular SQL statement updates three records on a table and there is an Update trigger defined on the table, then how many times will the trigger fire - three times or one time.

Thanks in advance.
Raj

View Replies !   View Related
Update Trigger
I have this table:

CREATE TABLE [dbo].[EB_Eprom] (
[EpromID] [int] IDENTITY (1, 1) NOT NULL ,
[Naam_Spel] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Versie] [nvarchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Checksum1] [nvarchar] (4) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Checksum2] [nvarchar] (4) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Omschrijving] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Datum_vrijgave] [smalldatetime] NULL ,
[Kabinet] [int] NULL ,
[Merk] [int] NULL ,
[Wet] [int] NULL ,
[Bestand_1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Bestand_2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Lastedit] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

and i created this trigger:

CREATE trigger CT_EB_EpromBestanden on dbo.EB_Eprom
after update
as
update EB_Eprom
set eb_eprom.bestand_1 = '../data/'+str(b.bestand_1) ,
eb_eprom.bestand_2 = '../data/'+str(b.bestand_2)
from EB_Eprom a join inserted b
on a.EpromID= b.EpromID


the thing that this trigger must do is update the given value with the custom path ../data/

Can someone tell me what i do wrong!!
Thanx already
Cheerz Wimmo

View Replies !   View Related
Update Trigger
hi folks.

Í want to do this:
/***************************************/
CREATE TRIGGER TRGfechaModificacion
ON UsuariosVencimientos
AFTER UPDATE AS
DECLARE @updatedID AS int
BEGIN
--Get the last ID updated
SELECT @updatedID = @@updated --???
-- Updated this record with the actual datetime
UPDATE
UsuariosVencimientos
SET
Fecha_Actualizacion = getDate()
WHERE
id = @updatedID
END
/***************************************/

Resume:

I want to get the 'id' updated so I can used for the update query ;)

thanx

View Replies !   View Related
TRIGGER FOR UPDATE
I HAVE TWO TABLES IN THE DATABSE T1 AND THE SECOND TABLE(T2) IS FOR AUDITING.
THE STRUCTURE OF BOTH THE TABLES IS SIMILAR WITH ONE MORE COLUMN 'STATUS' IN THE T2.
I HAVE ALREADY WRITTEN THE TRIGGERS FOR THE INSERT AND DELETE TRIGGERS SO THAT I CAN SAVE THE
RECORD WITH STATUS OF 'NEW INSERT' OR 'DELETE' OR 'UPDATE' IN THE AUDIT TABLE(T2).
HELP ME IN WRITING THE TRIGGER FOR UPDATE.
MY PROBLEM IS I DON'T KNOW HOW TO STORE THE UPDATED COLUMNS VALUES INTO VARIABLES AND SO THAT
I CAN STORE THE OLD VALUES INTO THE AUDIT TABLE(T2).
I M USING SQL SERVER 6.5, SO WE CAN NOT USE COLUMNS_UPDATED() IN THE TRIGGER.
PLEASE SUGGEST ME THE CODE SO THAT I CAN STORE THE OLD ROW IN THE TABLE(T1) TO TABLE (T2)
WITH STATUS 'UPDATE' IN THE T2.

PLEASE SUGGEST ME..ITS URGENT.

THANKS IN ADVANCE
HARISH




=============================
/*test trigger for insert status */
if exists (select * from sysobjects where id = object_id('dbo.tri_t1_insert') and sysstat & 0xf = 8)
drop trigger dbo.tri_t1_insert
GO

CREATE TRIGGER tri_t1_insert ON dbo.t1
FOR INSERT
AS
declare @v1 binary(20),
@v2 varchar(255)
Begin
select @v1=stamp,@v2=name from inserted
insert into t2(stamp,name,status) values(@v1,@v2,'NEW INSERT')
end
GO
========================================
/*test trigger for delete status */
if exists (select * from sysobjects where id = object_id('dbo.tri_t1_delete') and sysstat & 0xf = 8)
drop trigger dbo.tri_t1_delete
GO

CREATE TRIGGER tri_t1_delete ON dbo.t1
FOR delete
AS
declare @v1 binary(20),
@v2 varchar(255)
Begin
select @v1=stamp,@v2=name from deleted
insert into t2(stamp,name,status) values(@v1,@v2,'DELETE')

end

View Replies !   View Related
Update Trigger
Hello All,
How do I create an update trigger that only updates the record that is being updated?

TIA,
Terry

View Replies !   View Related
(Update) Trigger Help
I need to be able to select the row or specific field that was updated in an update trigger. I dont have any time-stamp or before-after value columns to compare. Please help!

View Replies !   View Related
Update Trigger
I have an update trigger on a table on my transactional database that inserts a row of data into another database (audit database)for any modification made on the transactional database.
So if i modify a row on tran db it will write the data modified as a new row in the audit db.

This works fine if I am updating only 1 row with each Update statement. However if I update more than 1 row (multiple rows) with the same Update statement, the update trigger only inserts the last row modified in the audit database. So I lose record of any other rows modified with the same update statement.

Is there a way by which i can change my Update trigger or something, so I get all the rows updated by 1 update statement inmy audit database???


Thanks a bunch,
Judy

View Replies !   View Related
Trigger Update?
Hello, I have two tables, looks as follow.

TOPIC
------
TOPIC_ID
STATUS_ID
TOPIC


THREAD
-------
THREAD_ID
TOPIC_ID
STATUS_ID
THREAD
THREAD_DATE
NAME

I want to update STATUS_ID in TOPIC when I post a new THREAD.
I guess the best would be to use a trigger?
Don't know much how you write them so if someone please could help or point me in right direction.
My plan is to always show the updated STATUS_ID in TOPIC while I have history in the THREAD TBL.
I am using MS SQL 7.0

Thanks for a great site.

Linkan

View Replies !   View Related
I Am Trying Do A Update With A Trigger?
Hello,

I am new to this and on my way to learning. I hope someone can help me with a trigger. I want to update status of one table when I insert a new threat in another. This is what I have come up with so far.

CREATE TRIGGER [trg_Update_Status] ON tForumThread
FOR INSERT
AS
BEGIN
UPDATE tJournalTopic (STATUS_ID)
SELECT STATUS_ID
FROM Inserted

Thanks,
Linkan

View Replies !   View Related
Update Trigger
I have multitude of tables which have one field value set to date as default. I hope to create a trigger which will automatically refresh this date field on any update to that row. I also hope to be able to reuse the same trigger for all other tables in my db. I.e. is it possible to automatically "refresh" this date field when row is updated?

View Replies !   View Related
Update Trigger
I am trying to Update a record (score_raw) in table 'sco_test', after an insert into the same name field (score_raw) in table 'scoHistory_test', for a specific StudentID and a specific CourseID.

The following works when I hard-code the data as in the following example:

CREATE TRIGGER scoUpdate ON [scoHistory_test]
AFTER INSERT
AS
UPDATE sco_test

SET sco_test.score_raw = '99'
WHERE sco_test.StudentID = '12345'
AND sco_test.CourseID = 'ABCD'

But when I substitute variables such as in the following:

SET sco_test.score_raw = scoHistory_test.score_raw
WHERE sco_test.StudentID = scoHistory_test.StudentID
AND sco_test.CourseID = scoHistory_test.CourseID

I get 'could not be boud' errors.

Any help would be greatly appreciated, as i am new to this.

View Replies !   View Related
Update On Trigger
Hi

i have a question on triggers

when i update a colum value of a table then
the row of the table with updated colum value
should be inserted in to other table.
i think u got my point.

for example

i have table customer with columns customerID,CustomerStatus,CustomerCity

i have another table  CustomerDetails with Colums CustomerID, CustomerStatus, etc

now if i update CustomerStatus in Customer Table

The colum in the row which i updated

the whole row should be inserted in to CustomerDetails Table.

CustomerDetails table contails all columns as in customer and more columns.

please someone help me
Thankyou

View Replies !   View Related
Update Trigger
Hello

i have two table parent & child,

if i'll update the foreign key in child table & updated value is not exits in parent then i have to update it as a null.

for that i have to write a trigger can any one help me for that.

 

View Replies !   View Related
UPDATE TRIGGER. HELP!!!
I created a trigger to change a personnel_id from another table if status field changed.

CREATE TRIGGER TR1

ON TABLE1

FOR UPDATE

AS

NOCOUNT ON

IF UPDATE (stataus_id)

BEGIN

If EXISTS (select * from inserted  i inner join deleted d on i.status_id=2 and i.status_id<>2)

UPADATE table1

SET Personnel_id= a. personnel_id from table 2 inner joing table 1 b on a.user_id=b.user_id

END

When I tried to update the next row after privious one updated I recievd a message :

Data has changed science tehResult pane was last retrieved. Do you want ti save you changes now?

Click YES to commit you changes to database.

Click No to discard your changes and Cancel to continue eding.

What I am doing wrong?

I quess I missed up something with inserted and deleted table?

Can anyone take a look on my script and help me?

Thanks

 

 

 

View Replies !   View Related
Update Trigger
 

Hello

i have two table parent & child,

if i'll update the foreign key in child table & updated value is not exits in parent then i have to update it as a null.

for that i have to write a trigger can any one help me for that.

View Replies !   View Related
Trigger For Update
I need help with a trigger(this is sql2000), So I have a certain table with a bunch of columns(ex table A [col1, col2, and col3]  i need to validate that only values of col2 can be updated, if the user tries to change the values of the other columns... then rollback.. raiserror.

So this is part of the code:

CREATE TRIGGER TRU_ServiceDetails ON ServiceDetails
FOR UPDATE
AS
BEGIN
DECLARE @ErrNr int, @ErrMesg varchar(255)

--Updates only can be made for the clomun Price
 IF EXISTS(SELECT * FROM Inserted I, ServiceDetails SD
   WHERE I.ServiceId=SD.ServiceId
   AND I.ServiceTypeID=SD.ServiceTypeID
   AND I.EmployeeID=SD.EmployeeID   AND I.ServiceDateTime=SD.ServiceDateTime

---so far i´m matching the rows of the two tables

the rest of the columns are : ReleaseDate, Location, Price (releasedate is the only column that can be updated)

--In The select I'm trying to match the ServiceDetails in Inserted with the ones on ServiceDetail, but i can´t bring up the error yet
    )

View Replies !   View Related

Copyright © 2005-08 www.BigResource.com, All rights reserved