Auditing - Trigger Or Stored Procedure

Dec 17, 2007


Hi All,

We have a requirement in the project to do auditing for some of the tables. We have come across different approaches of implementing auditing.

The following are the approaches:


Create a generic stored procedure to do auditing. Call this procedure whenever any tables that require auditing have insert/update/delete operation performed on it. Auditing and the DML operation should be part of a single transaction.
Create a generic CLR trigger to do the auditing. The CLR trigger can be attached to the tables that require auditing.
Create separate audit tables and triggers for each table which require auditing.

I would like to know whether there are any disadvantages of using triggers in production server. Could anyone please help me in identifying the best approach for implementing auditing?

Will there be any situation when the DML statements execute and the corresponding trigger fails?

Is there any performance degradation on using triggers for auditing compared to including the auditing logic implemented in the stored procedures? We have been advised not to use triggers in production environment. But we are not clear about the reason for this.

PLEASE NOTE THAT I DO NOT WANT TO REPLACE STORED PROCEDURE WITH TRIGGERS TO IMPLEMENT BUSINESS LOGIC. BUT IN THE SCENARIO THAT I DISCUSSED, I NEED TO CAPTURE THE LOG INFORMATION WHENEVE A DML STATMENT IS EXECUTED AGAINST THE TABLES. WHAT IS THE PREFERRED APPROACH HERE...USING TRIGGERS OR STORED PROCEDURES?

In general, is there any disadvantage in using triggers for auditing? Has anyone faced any issues with triggers? (Triggers not invoked during DML operations or any performance related issues) Please let us know.



Thanks,

View 3 Replies


ADVERTISEMENT

Auditing Trigger

Mar 20, 2006

hey all, i found this auditing trigger, currently it just kicks out what was changed and when, id like to add who cause the trigger to fire as well (currently its just set to the "inventory" table). check under the "add the audit fields" comment for info:

CREATE TRIGGER TRG_inventory
ON [DBO].[inventory]
FOR DELETE,INSERT,UPDATE
AS

DECLARE @ACT CHAR(6)
DECLARE @DEL BIT
DECLARE @INS BIT
DECLARE @SQLSTRING VARCHAR(2000)

SET @DEL = 0
SET @INS = 0

IF EXISTS (SELECT TOP 1 1 FROM DELETED) SET @DEL=1
IF EXISTS (SELECT TOP 1 1 FROM INSERTED) SET @INS = 1

IF @INS = 1 AND @DEL = 1 SET @ACT = 'UPDATE'
IF @INS = 1 AND @DEL = 0 SET @ACT = 'INSERT'
IF @DEL = 1 AND @INS = 0 SET @ACT = 'DELETE'

IF @INS = 0 AND @DEL = 0 RETURN

IF NOT EXISTS (SELECT * FROM SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[AUDIT_inventory]') AND OBJECTPROPERTY(ID, N'ISUSERTABLE') = 1)
BEGIN
-- CREATE A MEMORY TABLE CONTAINING THE FIELDS AND TYPES OF THE TABLE
DECLARE @MEMTABLE TABLE
(
ID INT IDENTITY
,COLUMNAME SYSNAME
,TYPENAME VARCHAR(20)
)
-- INSERT THE COLUMNAMES AND THE DATATYPES
INSERT @MEMTABLE
(COLUMNAME,TYPENAME)
SELECT NAME,TYPE_NAME(XTYPE)
FROM SYSCOLUMNS
WHERE ID = OBJECT_ID('[DBO].[inventory]')
ORDER BY COLID

DECLARE @CUR INTEGER
DECLARE @MAX INTEGER
DECLARE @SQLSTR AS VARCHAR(8000)
DECLARE @CURCOL SYSNAME
DECLARE @COLTYPE AS VARCHAR(10)

-- SETUP VARIABLES
SET @SQLSTR = ''
SET @CUR=1
SELECT @MAX = MAX(ID) FROM @MEMTABLE

-- LOOP EVEY FIELD
WHILE @CUR <= @MAX
BEGIN

-- GET VALUES FROM THE MEMTABLE
SELECT @CURCOL = COLUMNAME,@COLTYPE = TYPENAME FROM @MEMTABLE WHERE ID = @CUR
IF @COLTYPE = 'INT' OR @COLTYPE = 'BIGINT' OR @COLTYPE='UNIQUEIDENTIFIER'

-- WE DO WANT TO COPY INT/BIGINT/UNIQUEIDENTIFIER FIELDS BUT IF THEY ARE AN
-- IDENTITY OR A ROWGUIDCOLUMN WE DO NOT WANT TO COPY THOSE ATTRIBUTES

SET @SQLSTR = @SQLSTR + ' CAST('+@CURCOL + ' AS '+@COLTYPE+') AS [' + @CURCOL +'] '
ELSE

-- ANOTHER FIELD DO NOTHING JUST COPY IT AS IT IS
SET @SQLSTR = @SQLSTR + ' '+@CURCOL + ' AS [' + @CURCOL +'] '
IF @CUR <= @MAX - 1 SET @SQLSTR=@SQLSTR + ','
SET @CUR = @CUR + 1
END

-- ADD THE AUDIT FIELDS
SET @SQLSTR = @SQLSTR +',CAST('' '' AS CHAR(6)) AS TRG_ACTION,CAST(GETDATE() AS DATETIME) AS TRG_DATE ' - tryin to add who made the update here, figure out what GETUSER translates to

-- SET UP THE SELECT FOR CREATING THE AUDIT TABLE
SET @SQLSTR = 'SELECT TOP 0 ' + @SQLSTR + ' INTO [DBO].[AUDIT_inventory] FROM [DBO].[inventory]'
EXEC(@SQLSTR)
END

IF @ACT = 'INSERT' INSERT [DBO].[AUDIT_inventory] SELECT *,'INSERT' ,GETDATE() FROM INSERTED
IF @ACT = 'DELETE' INSERT [DBO].[AUDIT_inventory] SELECT *,'DELETE' ,GETDATE() FROM DELETED
IF @ACT = 'UPDATE' INSERT [DBO].[AUDIT_inventory] SELECT *,'UPDATE' ,GETDATE() FROM INSERTED

View 10 Replies View Related

Auditing Trigger

Apr 17, 2008

Hi


I would like to create a simple trigger on a Customer table to fullfill two fields, on should be filled when a new customer is inserted (DateAdded) and the other when the customer is edited (DateEdited), Yes I know it is quite simple but as I am not a database expert I do not know how to solve this problem.


Thank you in advance.

View 11 Replies View Related

Need Input On Trigger Based Database Auditing

Jun 5, 2008

Hi

I am building a pretty simple intranet application where we need to be able to track changes to tables. The tracking feature do not need to be very advanced, we just need to see who changed something and what it was. Therefore I decided just to use a trigger based solution, but need some input/advice since my SQL skills is somewhat lacking.

Consider the following (mock-up) schema:


-- My content table
CREATE TABLE [Content](
[ContentGuid] [uniqueidentifier] NOT NULL PRIMARY KEY DEFAULT (newid()),
[Data] [nvarchar](4000) NOT NULL,
[ChangedBy] [nchar](10) NOT NULL,
[MaybeNull] [int] NULL
)

-- My history table
CREATE TABLE [History](
[ChangedTable] [nvarchar](50) NOT NULL,
[ReferenceGuid] [uniqueidentifier] NOT NULL,
[ChangedBy] [nchar](10) NOT NULL,
[ChangedOn] [datetime] NOT NULL DEFAULT (getutcdate()),
[IsDelete] [bit] NOT NULL DEFAULT ((0)),
[Changes] [xml] NOT NULL
) ON [PRIMARY]

-- My insert/update trigger
CREATE TRIGGER [RecordChangeOnInsertUpdate]
ON [Content]
AFTER INSERT,UPDATE
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Changes xml
SET @Changes = (select * from [inserted] for xml raw ('Content'), elements xsinil)

INSERT INTO [History]
([ChangedTable]
,[ReferenceGuid]
,[ChangedBy]
,[ChangedOn]
,[IsDelete]
,[Changes])
SELECT 'Content', ContentGuid, ChangedBy, getutcdate(), 0, @Changes
FROM [inserted]
END

-- My delete trigger
CREATE TRIGGER [RecordChangeOnDelete]
ON [Content]
AFTER DELETE
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Changes xml
SET @Changes = (select * from [deleted] for xml raw ('Content'), elements xsinil)

INSERT INTO [History]
([ChangedTable]
,[ReferenceGuid]
,[ChangedBy]
,[ChangedOn]
,[IsDelete]
,[Changes])
SELECT 'Content', ContentGuid, ChangedBy, getutcdate(), 1, @Changes
FROM [deleted]
END


I have decided to use the "one history table for all table changes" method. The changes for a row is stored in a xml column which obviously limits the total size of columns in a table being tracked, but that is not a problem in my application. In general I like this set up, since I will be able to change the schema continuously without having to change the triggers, and since the application will probably evolve a lot over the coming months this is pretty important to me.

EDIT: I should add that all the tables I will be tracking have a uniqueidentifier column. This makes it possible to related table rows in the different tables being tracked with their history.

A few concerns with the above SQL:

- Can the inserted/deleted table change between "SET @Changes = (select * ..." and the "INSERT INTO ..." statement, such that the data is not valid? If so, how to work around that?

- If I were to (hypothetically) perform a "UPDATE [Content] SET [Data] = 'something'", not only is my update trigger called once for each row updated, but the XML added to the inserted row in the history table ([History].[Changes]) represent all the rows updated in the batch update. How do I get around this?

Are there any other issues I should be aware of?

Regards, Egil.

View 13 Replies View Related

Stored Procedure Or Trigger Or Both Or ???

Sep 20, 2006

HiThis problem involves 2 columns in my Product table - ReleaseDate(varchar) and ReleaseClass(varchar)When a new product is Entered, the current date is inserted into ReleaseDate & ReleaseClass = NewWhen product is a month old, I want ReleaseClass to = RecentWhen product is a month 3 mths old, I want ReleaseClass to = NormalWhen the product is a month old, is there a method to automatically run a Stored procedure say to change the ReleaseClass field??any code or links on how i go about this would be appreciated + i've never used a triggerCheers!!

View 5 Replies View Related

Trigger And Stored Procedure

Feb 14, 2007

What is trigger!what is differance beetween trigger and stored-Procedure!

View 1 Replies View Related

Trigger Vs Stored Procedure

Jan 12, 2006

Hi,
Please help me to find this answer.
We know Trigger are a type of stored procedure,and can be activated whether by a insert ,update or delete event of a table.
We also know that stored procedure are quick due to their execution plan which are already stored in the memory once complied.
But what about triggers?
what is the mechanism of triggers?How they work? And how fast they are from Tsql queries?Is there any mechanism to calculate or measure the efficiency of triggers?
Please comment if anybody knows the answers.
Thanks!!
Joydeep

View 2 Replies View Related

Get Return Value From Stored Procedure And Trigger

Oct 2, 2007

Hello there,
I searched for answers to the above topic, but could not find what I want. My stored procedures and triggers are returning a message based on the result, mostly error messages. How can I get that message using ASP.Net? Should I use an output parameter?
 Thank you for your help.

View 2 Replies View Related

Fire Trigger From Within A Stored Procedure Possible?

Oct 10, 2001

Is this possible?

View 1 Replies View Related

Trigger Calling Stored Procedure???

Mar 7, 2001

can a trigger firing cause a stored procedure to execute!! if this can be done then I will have more questions to follow! thanks, Scott

View 1 Replies View Related

Trigger Or Stored Procedure Question

Mar 11, 2005

I have a trigger that checks if a particular field in an application is being messed with. I am only allowing users to update this field when it is empty. So, I am not allowing them to change the value stored in the field (they will receive an email notification) because a backend operation is going on that could screw things up.

Aside from that, I want the application to refresh the page when the email goes out to go back and display the original contents of the field.

Now, I know this obviously cannot be done from a trigger since it is only dealing with the database. But, does someone have a quick and dirty way of accomplishing this?

Thanks

View 1 Replies View Related

Trigger Or Stored Procedure Question

Jan 16, 2008

Persons Table
PersonID int NOT NULL PRIMARY KEY
PersonFatherID int NULL FOREIGN KEY Persons(PersonID)
PersonMotherID int NULL FOREIGN KEY Persons(PersonID)
PersonGeneration int NULL
PersonFirstName nchar(20) NOT NULL
PersonLastName nchar(20) NOT NULL

Spouses Table
SpouseID int NOT NULL PRIMARY KEY
HusbandID int NOT NULL FOREIGN KEY Persons(PersonID)
WifeID int NOT NULL FOREIGN KEY Persons(PersonID)

Persons Table Data
PersonID PersonFatherID PersonMotherID PersonGeneration PersonFirstName PersonLastName
1 1 1 1 Adam Smith
2 2 2 1 Evelyn Smith
3 1 2 2 Caleb Smith
4 NULL NULL 0 Sara Jones

Spouses Table Data
SpouseID HusbandID WifeID
1 1 2
2 3 4

I want to update PersonGeneration column in Persons table when that person is added into Spouses table. For example, if Sara Jones is added as wife to Caleb Smith in Spouses table, then it should update Sara's PersonGeneration column (0) with Caleb's PersonGeneration (2) in Persons table. So, the rule is if PersonFatherID=NULL and PersonMotherID=NULL and PersonGeneration=0, then update this person's PersonGeneration with his/her spouse's PersonGeneration. I am thinking about a trigger or a stored procedure or both. Any help would be greately appreciated.

Thanks,
Mohan John

View 4 Replies View Related

Audit Trigger In Stored Procedure?

Dec 7, 2011

I have a requirement to audit tables in a SQL Server database. The tables are dynamically created when the application creates a form and the table holds the form data. So my plan is this, I have worked out the audit table (static) and the trigger. What i'm having issues with is getting the trigger to create from within the stored procedure. So just to recap: the user creates a form in the app, this creates a table and should call this stored procedure. The stored procedure creates the trigger on that table (which begins auditing that table, inserting to the static audit table based on the table name being passed into the stored procedure).

Where im at: I can create the stored procedure. When i go to run the stored procedure, I get the errors after passing the table as a value.

In my opinion it's an error with the correct number of single ticks, but not sure.

The Code:
USE [AdventureWorks]
GO
/****** Object: StoredProcedure [dbo].[spReplaceAuditTrigger] Script Date: 12/06/2011 15:28:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC spReplaceAuditTrigger( @PassedTableName as NVarchar(255) ) AS

[code].....

View 3 Replies View Related

Calling Stored Procedure In Trigger

Mar 17, 2004

Hi

I have a problem calling stored procedure in trigger..

When no exception occures stored procedure returns the value but if any exception occures executing that stored procedure then stored procedure will not return any value..

I have handled exception by returning values in case if any..

Here is the stored procedure

CREATE PROCEDURE BidAllDestinations
(
@ITSPID int,
@DestinationID int,
@BidAmount decimal (18,4),
@BidTime datetime,
@intErrorCode int out
)

AS
DECLARE @GatewayID int
DECLARE @GatewayExist int
SET @GatewayID = 0
SET @GatewayExist = 0
SET @intErrorCode = 0

UPDATE BID FOR CORRESPONDING GATEWAY
DECLARE GatewayList CURSOR FOR

SELECT Gateways.GatewayID
FROM Gateways INNER JOIN
GatewayDestinations ON Gateways.GatewayID = GatewayDestinations.GatewayID INNER JOIN
ITSPs ON Gateways.ITSPID = ITSPs.ITSPID
Where Gateways.ITSPID = @ITSPID AND DestinationID = @DestinationID

OPEN GatewayList

FETCH NEXT FROM GatewayList INTO @GatewayID

IF (@GatewayID = 0)

SET @intErrorCode = 1
ELSE
BEGIN
-- CHECK @@FETCH_STATUS TO SEE IF THERE ARE ANY MORE ROWS TO FETCH
WHILE @@FETCH_STATUS = 0

BEGIN


SELECT@GatewayExist = Gatewayid
FROMTerminationBids
WHEREGatewayid = @Gatewayid AND DestinationID = @DestinationID

IF @GatewayExist > 0

UPDATE TerminationBids
SET BidAmount = @BidAmount,
BidTime = getdate()

WHERE GatewayID = @Gatewayid AND DestinationID = @DestinationID

ELSE

INSERT INTO TerminationBids (GatewayID, DestinationID, BidAmount)
VALUES (@GatewayID,@DestinationID,@BidAmount)

IF @@ERROR <> 0
BEGIN
GOTO PROBLEM
CLOSE GatewayList
DEALLOCATE GatewayList
END

FETCH NEXT FROM GatewayList INTO @GatewayID

END
CLOSE GatewayList
DEALLOCATE GatewayList

END
PROBLEM:
BEGIN

SET @intErrorCode = 100


END
RETURN @intErrorCode
GO


TRIGGER CODE:::

CREATE TRIGGER TR_TerminationBid
ON dbo.TerminatorBidHistory FOR INSERT

AS

DECLARE @ITSPID int
DECLARE @DestinationID int
DECLARE @BidAmount decimal (18,4)
DECLARE @BidTime datetime
DECLARE @intErrorCode INT
DECLARE @DistinationList varchar (8000)
DECLARE @DestinationLevel varchar (100)
SET @intErrorCode = 0
SET @ITSPID = 0
SET @DistinationList = ''
-- CHECK ITPSID' S VALIDITY

SELECT@ITSPID = i.ITSPID, @DestinationID= i.DestinationID,
@BidAmount = i.BidAmount, @BidTime = i.BidTime
FROM Inserted i
INNER JOIN ITSPS ON ITSPS.ITSPID = i.ITSPID
INNER JOIN Destinations ON Destinations.DestinationID = i.DestinationID

EXEC BidAllDestinations @ITSPID,@DestinationID,@BidAmount,@BidTime, @intErrorCode = @intErrorCode output
SELECT @intErrorCode
Following should return value for @intErrorCode if any exception occures

Any one can help what is wrong with it?

Thanks

View 1 Replies View Related

Ytd Expenses---Trigger Or Stored Procedure

Oct 16, 2006

I'm trying to come up with a Stored Procedure or a Trigger to Sum up monthly =Expenses to the YTDExpenses Column. Can Someone help please.


I have a Monthlyexpense column. How do I Sum up this column and put the Total in my ytdexpenses column. Do I use a stored procedure, because I want the monthlyExpenses to SUm up every time I submit a monthly expense to the database and siplay in the ytdExpenses Column.
When I Write a Query all of the rows in the ytdExpenses shows the same amount and do not total up every time I submit to the database. Help please.

monthlyExpenses ytdExpenses
$1,000 $1,000
$2,000 $3,000
$3,000 $6,000
$2,000 $8,000
$5,000 $13,000

View 20 Replies View Related

How To Approach (Trigger-Stored Procedure )

Jul 20, 2005

Hi AllI need opinions on how to approach my task.I currently have 3 tables: the master table, the archive and a temptable.MASTER: has 3 fields ProductID and ProductNo and ReleasedARCHIVE: Has 3 ProductID, ProductNo, SoldDateTEMP: ProductID, ProductNo, SoldDateI have a trigger on the master table upon deletion to archive. This istriggered from a seperate routine from a vb app to delete a recordreal time.CREATE Trigger Archive_Proc On dbo.MASTERFor DeleteAsDeclare @iDate As DateTimeSet @iDate = GetDate()If @@RowCount = 0 Returnset Nocount onInsert Into ARCHIVE(ProductID, ProductNo, SoldDate)Select ProductID, ProductNo, @iDate from deletedMy problem is that I have a temp table that gets filled from aseperate transaction.It needs to be matched against the master tablethen deleted at both master and temp. but the issue is that the temptable contains its own SoldDate value that needs to be archived.Q 1: if I use a stored proc. how do i pass the SoldDate value to thetrigger as Triggers dont use GVs.Q 2: How do I set up the stored procedure to delete with multipletables. I can get it to UPDATE but not delete....CREATE PROCEDURE COMPARESOLD@Pool SmallintASSet NoCount onUpdate MASTERSet Released = 2From TEMP, MASTERWhere TEMP.ProductNo = MASTER.ProductNoAND TEMP.ProductID = MASTER.ProductIDAND INVENTORY.Released = 1hopefully someone can lead me to the right direction...Thanks

View 1 Replies View Related

Calling A Stored Procedure In A Trigger

Dec 10, 2007

Hello,

I am trying to test a simple trigger on insert and it does not work when I call EXEC sp_send_cdosysmail.
However, the stored procedures does work if I right-click on it and select Execute Stored Procedure.

Below is a simple version of the trigger I am trying to implement. I know it works in SQL Server 2000 and 2005 but can't seem to get it to work in SQL Server 2005 Express. Any help is greatly appreciated!


ALTER TRIGGER [dbo].[trig_Tableinsert]
ON [dbo].[Table]
FOR INSERT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.

Print 'Hello'

-- Insert statements for trigger here
EXEC sp_send_cdosysmail some@one.com', 'notify@me.com','New Insert', 'test'

END

Thanks!

View 5 Replies View Related

Trigger Or Stored Procedure Question

Jan 16, 2008

Persons Table
PersonID int NOT NULL PRIMARY KEY
PersonFatherID int NULL FOREIGN KEY Persons(PersonID)
PersonMotherID int NULL FOREIGN KEY Persons(PersonID)
PersonGeneration int NULL
PersonFirstName nchar(20) NOT NULL
PersonLastName nchar(20) NOT NULL


Spouses Table
SpouseID int NOT NULL PRIMARY KEY
HusbandID int NOT NULL FOREIGN KEY Persons(PersonID)
WifeID int NOT NULL FOREIGN KEY Persons(PersonID)


Persons Table Data
PersonID PersonFatherID PersonMotherID PersonGeneration PersonFirstName PersonLastName
1 1 1 1 Adam Smith
2 2 2 1 Evelyn Smith
3 1 2 2 Caleb Smith
4 NULL NULL 0 Sara Jones


Spouses Table Data
SpouseID HusbandID WifeID
1 1 2
2 3 4


I want to update PersonGeneration column in Persons table when that person is added into Spouses table. For example, if Sara Jones is added as wife to Caleb Smith in Spouses table, then it should update Sara's PersonGeneration column (0) with Caleb's PersonGeneration (2) in Persons table. So, the rule is if PersonFatherID=NULL and PersonMotherID=NULL and PersonGeneration=0, then update this person's PersonGeneration with his/her spouse's PersonGeneration. I am thinking about a trigger or a stored procedure or both. Any help would be greately appreciated.


Thanks,
Mohan John

View 1 Replies View Related

Execute A Trigger From Stored Procedure

Dec 26, 2007



Hi,

Is it possible to run trigger from a stored procedure?

View 1 Replies View Related

Using Trigger/Stored Procedure (Delete, Insert)?

Apr 18, 2008

I have 3 tables...TableA, TableB, TableC TableA - Personal InformationPersonalInfoId (Primary) , First Name,Last NameTableB - Personal Information To Department IDReferenceID, FKPersonalInfoId, FKDepartmentIdTableC - DepartmentDepartmentId, DepartmentNameI am coding Asp.Net VB using VWD express with Sql Server Express.  I know how to create a stored procedure to delete, insert and even update a record in TableA, TableB, TableC respectively.If I need to delete a record in TableC, which has a related record in TableB, I have read that I need to use a Trigger.  I never have used a Trigger and it is new to me.  Can someone point me a way on how to use one in this case of my deleting scenario.  Pretty much, if a user clicks on a delete button, and deletes a record in my TableC, I dont want a  FKDpartmentId in my TableB that doesnt exist anymore because it was deleted in TableC or prevent a user from deleting that record till the relationship in TableB is no longer valid. In the same vain, If I have a input form which ask the user to enter their First Name and Last Name and Department, i would like to add those records in TableA for First and Last Name, TableB for the Department.  Once again, how do I create a Trigger that if I insert a record in Table A to also insert the information for Department in Table B, if its successful in my stored procedure.  Hope that made sense.Thanks.   

View 2 Replies View Related

Disabling A Trigger From A Stored Procedure In Another Database

Nov 16, 2000

I want to disable a trigger on a table in a database from inside a stored procedure in another database.
Can I disable then enable? Do I have to drop then recreate the trigger?
How do I code it? I've tried several ways but I can't get it right...

View 1 Replies View Related

SQL Server 2005 Trigger Or Stored Procedure

Apr 10, 2008

I need to create either a trigger or stored procedure in SQL server 2005(hopefully someone can tell me).. Here is what I need to happen: I have a table with orders that are generated from a website. After the transaction is completed, I need have the record that was just created also copy to another table. There is a field called flag and the values in this field are either 1 or 2. Imediatly after the transaction occurs, I need the records where flag = 1 to copy to this other table. How would I go about doing this?

View 10 Replies View Related

Trigger Firing Multiple Stored Procedure

Jun 11, 2008

DESCRIPTION: I have an FTP server set up to log via ODBC into a table FTPLog. The trigger on table FTPLog fires when new files are received to process and load the file via a stored procedure.

CREATE TRIGGER tr_new_file ON FTPLog
AFTER INSERT
AS
SET NOCOUNT ON
DECLARE @filename varchar(50), @logtime datetime
DECLARE c1 CURSOR
FOR SELECT filename, logtime
FROM inserted
OPEN c1
FETCH NEXT FROM c1
INTO @filename, @logtime
WHILE @@fetch_status = 0
BEGIN
EXEC sp1 @filename, @logtime
FETCH NEXT FROM c_inserted
INTO @filename, @logtime
END
CLOSE c1
DEALLOCATE c1
END

PROBLEM: There are multiple problems with this setup. The first problem is that when the stored procedure gets executed it takes a long time to process the file and the FTP server never returned a completion code to the ftp client and ended with a connection time out from the client. My users keep asking if the FTP failed but it didnt fail. The server returned a completion code too late.

PROBLEM2: When multiple files are ftp to the server on the same session, only the first one gets process. Even though my code loops through all the records because the processing takes a long time the second one never gets executed. If I replace the EXEC sp1 statement with a PRINT statement then it's working fine.

SOLUTIONS and SUGGESTIONS highly appreciated.

View 13 Replies View Related

Maximum Stored Procedure, Function, Trigger, Or Vi

Mar 7, 2008

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 2 Replies View Related

Calling Asp.net Web Service From A Trigger Or Stored Procedure

May 6, 2008



Hi,
I need to call a webservice directly from a tigger or stored procedrue instead of creating a window service to read from a table then call the webservice .Is it possible ? if yes, please i need your support.
Thanks,

View 1 Replies View Related

@@Identity Being Over-written By Insert Trigger In Stored Procedure.

Oct 6, 2004

Hi All

I have a problem with an existing stored procedure that is used to insert a new entry to a table (using an Insert statement).

I have been using the @@Identity global variable to return the identity column (id column) back to the calling routine. This has worked fine for years until recently an ‘after insert Trigger’ has been added to the table being updated.

Now the @@Identity is returning the identity value of the trigger that was called instead of the original table insert.

Does anyone know how I can code around this issue (without using a select statement within my stored proc, as these have been known to cause locks in the past).

Thank in advance.

Eamon.

View 2 Replies View Related

Replicating Stored Procedure/trigger Permissions To Another Database

Feb 24, 2005

I need to come up with a script that when executed it will create a stored procedure and trigger along with permissions. Is there a way to make this into a package. Any ideas?

View 3 Replies View Related

Stored Procedure - Create Trigger File In Particular Directory

Oct 26, 2012

I created stored procedure to create trigger file in a particular directory using xp_cmdshell.

I am calling the procedure from windows batch script as follows

@@set osq200=osql /a 4096 /b /E /e /d %dbn% /m-1 /r 0 /S %dbs% /Q "exec SP_Create_TriggerFile %2,%1 "
@%osq200% >>%3rec.txt 2>%3rec_err.txt
@set dberr=%errorlevel%
@if %dberr% GTR 0 goto createDATriggerFileErr >>%3rec.txt

If the directory doesn't exist, its throwing error "The system cannot find the path specified" , but the %errorlevel% still showing as 0..

View 1 Replies View Related

SQL Server 2008 :: Create A Trigger With A Stored Procedure?

Jun 5, 2012

I am trying to create a trigger with in a stored procedure. When I execute the stored procedure I am getting the following error :

Msg 2108, Level 15, State 1, Procedure JPDSAD1, Line 1

Cannot create trigger on 'FRIT_MIP003_BOK_BTCH_LG.P62XB1.XB1PDS' as the target is not in the current database.

Here is the code for the stored procedure :

CREATE PROCEDURE [dbo].[InsertTRIGGER](@databaseA varchar(50))
AS
BEGIN
exec ('USE ['+@databaseA+'];')
exec ('CREATE TRIGGER [P62XB1].[JPDSAD1] ON [' + @databaseA + '].[P62XB1].[XB1PDS] ' +
'AFTER DELETE AS ' +
'BEGIN ' +
' INSERT INTO [' + @databaseA + '].[P62XB1].[XL1TDS] SELECT CAST(SYSDATETIME() AS DATETIME2(6)) , ''B'' , ''D'' , IDA_DELETE ' +
' ''0001-01-01 00:00:00.000000'' , '' '' FROM DELETED ' +
'END')
END

View 5 Replies View Related

Trigger Executing Linked Server Stored Procedure

Jul 3, 2006

What is the syntax for creating a update trigger and passing the values which were updated to a stored procedure on a linked server?? Specifically need syntax for updated value, as well as the syntax for executing the stored proc on the linked server.

Thank you

View 1 Replies View Related

Is There A Way To View Stored Procedure, Trigger AndFunction Usage In SQL Server?

Oct 11, 2006

I am maintaining an application where most of the business rules are inTriggers, Stored Procedures and User Defined Functions. When a bugarises, it can get very tedious to debug. Today for example, I wantedto modify a function that was being called by a trigger. The problemis that I don't want to change the function, for fear that it is beingcalled by one of the other SP's or triggers in the database (there arehundreds of them)Essentially, I need a tool that allows me to view where functions andsp's are being referenced from. At the very least, I'd like to performa "full text search" in the database objects, so that let's say I havea function named "fn_doSomething", I can search the schema for thisstring and get all the places where it appears.As you can see, I'm in the dark here. I've never worked on a systemwhere all business rules are at the database level. If you know of atool that does what I describe above, or anything else that wouldfacilitate my life, please let me know!Thanks for your help,Marc

View 5 Replies View Related

Instead Of Insert, Update Trigger Calling A Stored Procedure Question

Oct 26, 2006

I have to control my business rules in a Instead of Insert, Update Trigger.

Since the Control Flow is quite complicated I wanted to break it into stored procedures that get called from within the trigger.

I know that Insert Statements embedded in a Instead of Trigger do not execute the Insert of the trigger you are calling.



But... If I embed stored procedures that handle my inserts in the Instead of Insert trigger call the trigger and put in a endless loop or are the stored procedure inserts treated the same as trigger embedded inserts.

View 7 Replies View Related

SQL Server 2008 :: Trigger To Show Which Stored Procedure Has Updated A Table

Jul 9, 2015

I am looking to created a trigger that inserts records into a log table to show the stored porcedure that has updated a specific column to a specific value in a specific table

At present I have:

CREATE TRIGGER [dbo].[trUpdaterTable]
ON [dbo].[t_account]-- A DB level trigger
FOR UPDATE
--Event we want to capture
AS
IF update (document_status)

[Code] ...

However this doesn't appear to bring back the procedure that triggered the update...

The value the trigger should update on is document_status = 0

DDLProcExecutedByEventDate
NULLNULLLOMBDAadministrator2015-06-25 07:42:01.677
NULLNULLLOMBDA im64602015-06-25 07:51:34.503
NULLNULLLOMBDAadministrator2015-06-25 07:52:01.610
NULLNULLLOMBDAadministrator2015-06-25 08:02:01.417
CREATE TRIGGER [dbo].[trTableupdateaccount] ON [DoesMore].[dbo].[t_account]

[Code] ....

View 9 Replies View Related







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