Getdate() In Insert Trigger
Jun 10, 2008
Hi all,
I am trying to create a trigger for a table, when a record is inserted into the table, the currdate_time field should be inserted with the current date and time. I tried below in Oracle
create trigger test_trg
before insert on test
for each row
begin
:new.curr_datetime := sysdate;
end;
/
For Sql server, I tried the below,
create table test (num smallint, curr_datetime datetime)
go
create trigger test_trg
on test
for insert
as
insert into test (curr_datetime) select getdate() from dual
I inserted a record into test:
insert into test (num) values (8)
select * from test
num curr_datetime
8 NULL
NULL 2008-06-10 09:49:06:317
Trigger is inserting NULL values. Please give me your suggestions.Thanks.
View 17 Replies
ADVERTISEMENT
May 28, 2008
I have a trigger on a table that basically logs changes to another table. Something like this:
Code Snippet
...AFTER INSERT
insert into LogTable
select RowID, GetUTCDate()
from INSERTED
Here's the question: Using GetDate() or GetUTCDate(), if the INSERT query within the trigger takes 20 seconds, will all records inserted into LogTable be inserted with an identical date value, or will the last records inserted have a date value 20 seconds greater than the first records?
In essence, What is the scope or duration of using GetDate() ?
View 3 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
Jan 14, 2008
This problem is being seen on SQL 2005 SP2 + cumulative update 4
I am currently successfully using the output clause of an insert statement to return the identity values for inserted rows into a table variable
I now need to add an "instead of insert" trigger to the table that is the subject of the insert.
As soon as I add the "instead of insert" trigger, the output clause on the insert statement does not return any data - although the insert completes successfully. As a result I am not able to obtain the identities of the inserted rows
Note that @@identity would return the correct value in the test repro below - but this is not a viable option as the table in question will be merge replicated and @@identity will return the identity value of a replication metadata table rather than the identity of the row inserted into my_table
Note also that in the test repro, the "instead of insert" trigger actually does nothing apart from the default insert, but the real world trigger has additional code.
To run the repro below - select each of the sections below in turn and execute them
1) Create the table
2) Create the trigger
3) Do the insert - note that table variable contains a row with column value zero - it should contain the @@identity value
4) Drop the trigger
5) Re-run the insert from 3) - note that table variable is now correctly populated with the @@identity value in the row
I need the behaviour to be correct when the trigger is present
Any thoughts would be much appreciated
aero1
/************************************************
1) - Create the table
************************************************/
CREATE TABLE [dbo].[my_table](
[my_table_id] [bigint] IDENTITY(1,1) NOT NULL,
[forename] [varchar](100) NULL,
[surname] [varchar](50) NULL,
CONSTRAINT [pk_my_table] PRIMARY KEY NONCLUSTERED
(
[my_table_id] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, FILLFACTOR = 70) ON [PRIMARY]
)
GO
/************************************************
2) - Create the trigger
************************************************/
CREATE TRIGGER [dbo].[trig_my_table__instead_insert] ON [dbo].[my_table]
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO my_table
(
forename,
surname)
SELECT
forename,
surname
FROM inserted
END
/************************************************
3) - Do the insert
************************************************/
DECLARE @my_insert TABLE( my_table_id bigint )
declare @forename VARCHAR(100)
declare @surname VARCHAR(50)
set @forename = N'john'
set @surname = N'smith'
INSERT INTO my_table (
forename
, surname
)
OUTPUT inserted.my_table_id INTO @my_insert
VALUES( @forename
, @surname
)
select @@identity -- expect this value in @my_insert table
select * from @my_insert -- OK value without trigger - zero with trigger
/************************************************
4) - Drop the trigger
************************************************/
drop trigger [dbo].[trig_my_table__instead_insert]
go
/************************************************
5) - Re-run insert from 3)
************************************************/
-- @my_insert now contains row expected with identity of inserted row
-- i.e. OK
View 5 Replies
View Related
Mar 1, 2004
Hi
I am trying to use multiple insert for a table T1 to add multiple rows.
Ti has trigger for insert to add or update multiple rows in Table T2.
When I provide multiple insert SQL then only first insert works while rest insert statements does not work
Anybody have any idea about why only one insert works for T1
Thanks
View 10 Replies
View Related
Oct 4, 2000
Please i need an exmple of ur solution, thanks :)
I'm using some files to show certain pages on certain date for an example
File name : aa.doc
start date: 10/02/00
end date : 10/03/00
But it expires on 10/02/00, here is the strored procedure:
Before the date comes, it expires the page
Here is my stored procedure:
"
SELECT startdate, enddate,archivedate
and (startdate is null or (getdate() >= startdate and getdate() <= enddate))
and (archivedate is null or (getdate() <= archivedate))
group by startdate, enddate order by startdate desc "
Thankx a lot
View 1 Replies
View Related
Nov 12, 2007
Hi,
We need to select rows from the database that have been recently inserted/updated. We have a main primary table (COMMIT_TEST) and a second update table (COMMIT_TEST_UPDATE). The update table contains the primary key and a LAST_UPDATE field which is a datetime (to tell us when an update occurred). Triggers on the primary table are used to populate the update table.
If we insert or update the primary table in a transaction, we would expect that the datetime of the insert/update would be at the commit, however it seems that the insert/update statement is cached and getdate() is executed at the time of the cache instead of the commit. This causes problems as we select rows based on LAST_UPDATE and a commit may occur later but the earlier insert timestamp is saved to the database and we miss that update.
We would like to know if there is anyway to tell the SQL Server to not execute the function getdate() until the commit, or any other way to get the commit to create the correct timestamp.
We are using default isolation level. We have tried using getdate(), current_timestamp and even {fn Now()} with the same results. SQL Queries that reproduce the problem are provided below:
/* Different functions to get current timestamp €“ all have been tested to produce the same results */
/*
SELECT GETDATE()
GO
SELECT CURRENT_TIMESTAMP
GO
SELECT {fn Now()}
GO
*/
/* Use these statements to delete the tables to allow recreate of the tables */
/*
DROP TABLE COMMIT_TEST
DROP TABLE COMMIT_TEST_UPDATE
*/
/* Create a primary table and an UPDATE table to store the date/time when the primary table is modified */
CREATE TABLE dbo.COMMIT_TEST (PKEY int PRIMARY KEY, timestamp) /* ROW_VERSION rowversion */
GO
CREATE TABLE dbo.COMMIT_TEST_UPDATE (PKEY int PRIMARY KEY, LAST_UPDATE datetime, timestamp ) /* ROW_VERSION rowversion */
GO
/* Use these statements to delete the triggers to allow reinsert */
/*
drop trigger LOG_COMMIT_TEST_INSERT
drop trigger LOG_COMMIT_TEST_UPDATE
drop trigger LOG_COMMIT_TEST_DELETE
*/
/* Create insert, update and delete triggers */
create trigger LOG_COMMIT_TEST_INSERT on COMMIT_TEST for INSERT as
begin
declare @time datetime
select @time = getdate()
insert into COMMIT_TEST_UPDATE (PKEY,LAST_UPDATE)
select PKEY, getdate()
from inserted
end
GO
create trigger LOG_COMMIT_TEST_UPDATE on COMMIT_TEST for UPDATE as
begin
declare @time datetime
select @time = getdate()
update COMMIT_TEST_UPDATE
set LAST_UPDATE = getdate()
from COMMIT_TEST_UPDATE, deleted, inserted
where COMMIT_TEST_UPDATE.PKEY = deleted.PKEY
end
GO
/* In our application deletes should never occur so we don€™t log when they get modified we just delete them from the UPDATE table */
create trigger LOG_COMMIT_TEST_DELETE on COMMIT_TEST for DELETE as
begin
if ( select count(*) from deleted ) > 0
begin
delete COMMIT_TEST_UPDATE
from COMMIT_TEST_UPDATE, deleted
where COMMIT_TEST_UPDATE.PKEY = deleted.PKEY
end
end
GO
/* Delete any previous inserted record to avoid errors when inserting */
DELETE COMMIT_TEST WHERE PKEY = 1
GO
/* What is the current date/time */
SELECT GETDATE()
GO
BEGIN TRANSACTION
GO
/* Insert a record into the primary table */
INSERT COMMIT_TEST (PKEY) VALUES (1)
GO
/* Simulate additional processing within this transaction */
WAITFOR DELAY '00:00:10'
GO
/* We expect at this point that the date is written to the database (or at least we need some way for this to happen) */
COMMIT TRANSACTION
GO
/* get the current date to show us what date/time should have been committed to the database */
SELECT GETDATE()
GO
/* Select results from the table €“ we see that the timestamp is 10 seconds older than the commit, in other words it was evaluated at */
/* the insert statement, even though the row could not be read with a SELECT as it was uncommitted */
SELECT * FROM COMMIT_TEST
GO
SELECT * FROM COMMIT_TEST_UPDATE
Any help would be appreciated, we understand we could make changes to the application/database to approximate what we need, but all the solutions have identified suffer from possible performance issues, or could still lead to missing deals (assuming the commit time is larger than some artifical time window).
Regards,
Mark
View 8 Replies
View Related
Nov 25, 2006
In case of a bulk insert, the “FOR INSERT� trigger fires for each recod or only once?
Thanks,
View 1 Replies
View Related
Nov 20, 2006
I would like to have the value of a field to be set the return value of
System.Web.Security.Membership.GeneratePassword(12,4)
every time a a row is inserted.
Can you guide with this?
Do you have some similar sample code?
Thank you very much
View 1 Replies
View Related
Dec 3, 2006
I would like to have the value of a field to be set the return value of
System.Web.Security.Membership.GeneratePassword(12,4)
every time a a row is inserted.
Can you guide with this?
Do you have some similar sample code?
Thank you very much
View 1 Replies
View Related
Nov 12, 2001
Should a insert trigger fire my update trigger as well? it fires it automatically after the insert? Is this a bug?
View 1 Replies
View Related
Aug 31, 2000
I have to create a insert trigger that calls a stored procedure usp_a
I need to pass two parameters to this stored procedure, value coming from the row inserted...
What is the syntax? Any help will be appreciated?
View 1 Replies
View Related
Jan 14, 2005
Hi.
Replication is not an option for me so I am trying to creat a trigger that will basically copy any new record to another database. I am using an on insert trigger and I get all records from the table inserted to the new db not just the new record.
Any ideas?
Thanks.
Bill
View 4 Replies
View Related
Apr 26, 1999
I am trying to write a pre-insert trigger. I want a row to be deleted first and then have the new row inserted. The end result is an insert/update statement. If anyone knows how to do this or has a better way, let me know, Please.
View 3 Replies
View Related
Oct 13, 1998
I am trying to write an insert trigger for the following problem. I have a table that contains a field (amount) that contains currency amount. Each row could be a record from a transaction in a different country. I would like each record to be converted into U.S. currency as it is inserted. So I created an other table that contains that exchange rate. How can I create a trigger that does this?
Tax Detail Table Exchange Table
Account# int Country char
Description char ExchangeRate Money
Amount money
Country char
I am working with MSS 6.5. Any and all help will be greatly appreciated.
Fidencio Peña
View 3 Replies
View Related
Dec 8, 1998
MSSQL 6.5
Is there any way to change some columns on inserted lines in ON INSERT trigger?
My notice: I try to find something about it in SQLBOOKS, but I found nothing.
It's possibly not TRUEEE!!!!! It wants me to grumble.
Thank for your answer.
View 1 Replies
View Related
Nov 28, 2005
Really simple question - I have the following trigger for the INSERT event for Tbl_B:
CREATE TRIGGER calc_total ON [dbo].[Tbl_B]
FOR INSERT
AS
DECLARE @VATRate AS decimal(19,2)
SET @VATRate = (
SELECT Val
FROM Tbl_Numeric_Refs
WHERE Ref = 'VATRate'
)
UPDATE Tbl_B
SET [Total] = ((@VATRate / 100) * [PriceA]) + [PriceA],
[VATRate] = @VATRateHow can I restrict the UPDATE within the trigger to the record(s) being INSERTed? Or am I over-complicating things, and should use a simple UDF for this instead?
View 2 Replies
View Related
Oct 22, 2007
Is it possible to pick up the value that is being inserted within the scope of a trigger? For example, if I were to run the following
INSERT INTO people (firstname, lastname)
VALUES ('George', 'V')
Would it be possible to access these values in a trigger before they are inserted?
CREATE TRIGGER trigger1
ON people
FOR INSERT
AS
IF EXISTS (SELECT 1 FROM table1 WHERE firstname = <the value being inserted>) BEGIN
Print '1'
END
ELSE BEGIN
Print '2'
END
GO
View 4 Replies
View Related
Nov 15, 2007
Rightio - this is probably a simple question for you SQL afficionados.I have written a trigger to update a master table with a CreateDate field. Simple enough I thought but it updates this field when the existing record is edited as well - not so good.This is how it looks like:CREATE TRIGGER CreateDateON MasterFOR UPDATE ASDECLARE@idMaster intSELECT @idMaster = idMaster from Insertedupdate Masterset CreatedDate = getdate()where idMaster = @idMasterGOWell I know I can write an IF statement that will basically say if the field is not null then only update - fair enough - but is there a simpler way to do this? Is there a way I need to write my CREATE TRIGGER statement that ONLY makes it run when it is a NEW INSERT ONLY?THANKS!
View 8 Replies
View Related
Jan 27, 2004
Hi, i'm a newbie in writting trigger and stored procedure, need to get help on this:
I cannnot find anyway to run the trigger before insert, anyway to do this?
Thanks.
View 2 Replies
View Related
Mar 2, 2004
So... dear friends
I want to insert values to a table without firing the foreign key Constraint.
I think one way is to insert values into the parent table first and then perform the initial insert.
Is this possible with an INSTEAD OF INSERT Trigger or another way? If yes can you make an example? I want to check for dublicate values in the parent table too!!
Thanx!
View 6 Replies
View Related
May 4, 2008
I have an EMPLOYEE table and DEPARTMENT table, i have to create one to many relationship where one employee can be in many departments, please guide me
create table employee (e_id INTEGER, e_fname varchar(30), e_lname varchar(30), d_id INTEGER references department(d_id))
create table department (d_id INTEGER, d_name varchar(30))
but here the problem would be while inserting into employee table since i have no primary key... do i need to use trigger to insert the right values.
View 10 Replies
View Related
May 18, 2008
I'm having table as below,
StudentEnroll_Thismonth
TransID(AutoNumber) | StudentID | Subject | TransDate
------------------------------------------------
1 | 0021 | A890 | 4/1/2008
2 | 0021 | A830 | 4/1/2008
3 | 0025 | A890 | 4/1/2008
4 | 0025 | A112 | 4/1/2008
5 | 0026 | A545 | 4/1/2008
.............
.............
99 | 0021 | A900 | 4/30/2008
100 | 0021 | A902 | 4/30/2008
101 | 0025 | A900 | 4/30/2008
*The table above contains what subject taken by student
Let's say, GETDATE()=5/1/2008
If execute Trans-SQL below,
INSERT INTO StudentEnroll_ThisMonth(StudentID,Subject,TransDate) values(0023,'B328',GETDATE())
How the trigger looks like to make sure the data in table shown as follow,
StudentEnroll_Thismonth
TransID(AutoNumber) | StudentID | Subject | TransDate
-----------------------------------------------------------
120 | 0023 | B328 | 5/1/2008
*All the previous month record move to StudentEnroll_PreviousMonth automatically
StudentEnroll_PreviousMonth
TransID(AutoNumber) | StudentID | Subject | TransDate
------------------------------------------------
..................
..................
..................
200 | 0021 | A890 | 4/1/2008
201 | 0021 | A830 | 4/1/2008
203 | 0025 | A890 | 4/1/2008
204 | 0025 | A112 | 4/1/2008
205 | 0026 | A545 | 4/1/2008
.................
.................
301 | 0021 | A900 | 4/30/2008
302 | 0021 | A902 | 4/30/2008
303 | 0025 | A900 | 4/30/2008
Anyone can help me to show the trigger?
View 4 Replies
View Related
Jun 5, 2008
Hi there,
After some head scratching and much research and trying I am unable to figure out how to do the following Insert Trigger. Maybe it shows a flaw in my database design?
I have a user front end where a user can assign a certain job to be done and assign it to one and only one shift and one or more equipments to do this job on.
When user clicks on Assign button it will insert rows into Jobs table via an insert stored procedure. Jobs table has following fields : ShiftID, and a JobEquipmentID since Job can be done on one or more equipment. This field, JobEquipmentID, will refer to a child table JobEquipment. What is the best approach to update this secondary table? I need to update JobEquipmentID but I do not have it until I update JobEquipment table? CRAZY!!! HELP
View 16 Replies
View Related
Jun 10, 2008
I'm new to triggers but basically what I want to do is the following, I have 2 databases name Prod and Dev In the Prod database I have a table call Sales I’m only interested in the Sale_ID field. On the Dev database I have a table call QMD and once more I’m only interested in the Sale_ID field. What I would like to do is as soon as a new record gets created in the Sales table located in the Prod database I would like to grab the Sale_ID and create a new record on the QMD table of the Dev database with the same Sale_ID, and leaving the other field blank of the newly created record.
Thank You
View 3 Replies
View Related
Oct 5, 2007
Hi,
I need to update a createdDt field,
with currentdate only when there is a insert in the table.
Please help me with how to do this.
Thanks
View 4 Replies
View Related
Jan 10, 2008
I have an Insert Trigger on the table
I would like to know what would happen when record gets inserted from GUI(using stored procedure).
1. Record gets inserted into table , then trigger fires and stored procedure sends output to GUI.
2. Record gets inserted stored procedure sends output and then trigger fires.
Thanks
View 2 Replies
View Related
Feb 3, 2008
Dear all,
I have a table named Messages with fields
Id numeric
SmsBody varchar(4000)
mobilenumber varchar(15)
Status char(1).
and also there is another table named MsgHistory with fields
Id numeric
MsgId numeric -- (will be the Id from table Messages)
SmsBody varchar(4000)
Status char(1).
I need to work a trigger if any new message (record) is inserted into table Messages, at the same time the trigger should execute to insert MsgId and SmsBody to table MsgHistory from table Messages.
How I can write trigger for this?
with regards
Shaji
View 1 Replies
View Related
Jul 23, 2005
Hello,I'm new with triggers and I can not find any good example on how todo the following:I have two tables WO and PM with the following fields:WO.WONUM, VARCHAR(10)WO.PMNUM, VARCHAR(10)WO.PROBLEMCODE, VARCHAR(8)WO.LABORGROUP, VARCHAR(8)PM.PMNUM, VARCHAR(10)PM.PROBLEMCODE, VARCHAR(8)PM.LABORGROUP, VARCHAR(8)When creating a new record on WO I need to create an INSERT TRIGGERthat will pass the data below from PM to WO when WO.PMNUM = PM.PMNUMPM.PROBLEMCODE to WO. PROBLEMCODE andPM.LABORGROUP to WO. LABORGROUPCould anybody please show me how to do this or point me to the rightdirection, any help will be greatly appreciated.Thanks!Martin
View 9 Replies
View Related
Jun 28, 2006
HiI have a table - DebtorTurnover - consisting of 5 fields (ID, Date,Turnover, VAT, Netturnover). I get a file which I have to import everyknow and then, with new data. In this file I only get values for (ID,Date, Turnover and VAT). The import is working fine with the importwizard.The problem is, that I want to have the Netturnover computed at thetime of insert to equal [Turnover-VAT], but I don't really know how toas I'm new to these triggers.Could anyone help me I would appriciate this.BR / Jan
View 3 Replies
View Related
Jun 27, 2006
Hi,
I've a SMS gateway that inserts SMS message into a varchar column. However, when it receives a SMS with single quote, it fails to insert into the varchar column. E.g., It's a...How's life ?....
I need help to find a workaround. Is there a equivalent of Before Insert trigger ? Also realised that the locgical 'inserted' table cannot be updated.
Advice pls.
View 4 Replies
View Related
May 13, 2006
I have a table that has a unique ID field. When a new record is
inserted into the table I would like to insert the ID into 3 other
tables. I am new to triggers and am not sure how to handle
this. Any idea how the trigger would be written?
View 3 Replies
View Related