473,851 Members | 2,297 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

creating trigger to auto set create/modify dates

Hi,

I'm a newbie to sql server and this may be a really dumb question for
some you. I'm trying to find some examples of sql server triggers that
will set columns (e.g. the created and modified date columns) if the row
is being inserted and set a column (e.g. just the modified date column)
if the row is being updated.

I know how to do this in oracle plsql. I would define it as a before
insert or update trigger and reference old and new instances of the
record. Does sql server have an equivalent? Is there a better way to do
this in sql server?

Thanks
eric

this is what i do in oracle that i'm trying to do in sqlserver...

CREATE OR REPLACE TRIGGER tr_temp_biu
before insert or update
on temp
referencing old as old new as new
for each row
begin
if inserting then
:new.created_da te := sysdate;
end if;
:new.modified_d ate := sysdate;
end tr_temp_biu;
Jul 20 '05 #1
1 17348
On Thu, 07 Oct 2004 13:02:41 -0400, efinney wrote:
Hi,

I'm a newbie to sql server and this may be a really dumb question for
some you. I'm trying to find some examples of sql server triggers that
will set columns (e.g. the created and modified date columns) if the row
is being inserted and set a column (e.g. just the modified date column)
if the row is being updated.

I know how to do this in oracle plsql. I would define it as a before
insert or update trigger and reference old and new instances of the
record. Does sql server have an equivalent? Is there a better way to do
this in sql server?

Thanks
eric

this is what i do in oracle that i'm trying to do in sqlserver...

(snip)

Hi Eric,

Don't try to do a one on one translation from Oracle to SQL Server. The
differences are too big (especially when it comes to triggers and other
non-ANSI-standard syntax).

For the creation date, no trigger is needed. Simply use a default. Use the
same default for the modified date if you want that set at the time a row
is inserted as well. If you rather leave the moodified_date NULL until the
row actually is updated, remove the default and change NOT NULL to NULL.

CREATE TABLE MyTable (KeyCol1 int NOT NULL,
KeyCol2 char(6) NOT NULL,
DataCol1 varchar(130) NULL,
DataCol2 datetime NOT NULL,
Created_Date datetime NOT NULL
DEFAULT (CURRENT_TIMEST AMP),
Modified_Date datetime NOT NULL
DEFAULT (CURRENT_TIMEST AMP),
PRIMARY KEY (KeyCool1, KeyCol2)
)

There are no BEFORE triggers in SQL Server. Only AFTER and INSTEAD OF
triggers are supported. In your case, I'd use an AFTER trigger. A very
fundamental difference that you should really be aware of, is that SQL
Server executes a trigger once per update (insert, delete) statement, with
all affected rows in the inserted and deleted pseudo-tables. All Oracle
triggers I've seen so far are processed for each individual row - a very
big difference that can lead to spectacular errors.

CREATE TRIGGER MyTrigger
ON MyTable
AFTER UPDATE
AS
-- Prevent recursion!
IF NOT UPDATE(Modified _Date)
BEGIN
UPDATE MyTrigger
SET Modified_Date = CURRENT_TIMESTA MP
WHERE EXISTS (SELECT *
FROM inserted AS i
WHERE i.KeyCol1 = MyTable.KeyCol1
AND i.KeyCol2 = MyTable.KeyCol2 )
END

(untested)
UPDATE MyTable

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 20 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3924
by: kk | last post by:
Hello, Help! Does anyone have an example of a trigger that will export a newly inserted row into a flat file? Basically anytime a row is inserted into a specific table a flatfile (fixed width) should be created in a hardcoded directory. I have the export command created but it doesn't seem to work in a trigger. I am sort of a newb to DB2 (at least its more advanced functions). I have a project going 'live' and I have no idea on how...
3
4868
by: gimme_this_gimme_that | last post by:
Hi, Start up db2 8.2 as "db2 -td@" and execute the following command : CREATE OR REPLACE TRIGGER "BZ".ALERT_CREATED_DATE BEFORE INSERT ON TS_ALERTS REFERENCING OLD AS OLD NEW AS NEW FOR EACH ROW BEGIN ATOMIC
5
6535
by: Mal | last post by:
Hello. I have a database that tracks reservations at a campground. I want to be able to make a calendar type report that shows how many people are here in given period. Stored for each reservation are dteReservationFROM (The date they come in) dtrReservationTO (The date they leave)
5
1598
by: hwt | last post by:
Hi Please excuse my poor description of the task. I have to make a report for my database. I need to have a report for each month. I need to make it so that each report contains every weekday of the month and places the results into a table, which has 7 columns. The other 6 columns need to provide a True/False grid based on the column titles(Session Names), which are the same on all reports. The True/False part needs to be filled in...
1
1640
by: abhu50 | last post by:
hiiiiiiii i wan to create trigger for table emp0 attribute are:- eno ename sal dno now i want to contro insertion on emp0 by using trigger that will allow only those record having salary greater than 1000 otherwise will not insert record. plzzzzzzzz help me
3
1474
by: pravatjena | last post by:
Hi Plz solve my problem....... My problem is i have created three users suppose user1 user2 user3 i created a table in user1 then i created a table in user3 same as the table in user1 but name is differnt and i created a triger in user2. then i want the trigger should insert the inserted or updated or deleted records in user1 table to user3 table...also i have given all the required previllages still the trigger cant do the required...
1
1176
by: arggg | last post by:
Does anyone know of webhosting that will allow the auto create of email addresses (such as the ones that craigslist.com uses when a new item is setup to be sold) without me having to go into the webpanel and add them manually?
0
1166
by: Dave Smith | last post by:
I’m looking for a way to have my queries headers change their dates automatically each month or when the date changes. I have a query that exports to an excel file. My query changes automatically each month with using the formula below Month12: Min((IIf( Between DateSerial(Year(Date()),Month(Date())-12,1) And DateSerial(Year(Date()),Month(Date())-11,0),))) Basically when I run the update query and the new month populates the formula...
1
1852
by: Ching Li | last post by:
Hi Lets say I have a table MyUser (column: MyuserID, Username) Another table Product (column: ProductID, ProductName) Then I created a table MyUser_Audit (column: MyUserID, Username, audit_action, Audit_Timestamp) to store all the audit trail. And now, user01 with name Mary inserted ProductID and ProductName into the Product table.
0
11011
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10670
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10352
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7900
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7072
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5735
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4547
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4142
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3178
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.