@@TRANCOUNT Difference Between SQL 7 And SQL 2000 In Trigger
Jul 20, 2005
During testing of an application, i noticed a difference between
SQL 2000 and SQL 7, both with identical config.
In a nutshell:
A table has a trigger for UPDATE and DELETE.
When a column in the table is UPDATED the following happens:
In autocommit mode, when entering a trigger the trancount equals
1 for both SQL 7 and 2000.
When the same update is performed in an explicit transaction
in SQL 7 @@TRANCOUNT equal 2, and in SQL 2000 @@TRANCOUNT equals 1.
Configuration is the same and there are no implicit transactions.
I don't need a work around as this will invalidate the migration
process as both products should behave identically.
What would influence the difference or why is there a difference???
Is there something which has been overlooked?
================================================== =======
The following code replicates the problem
Ensure implicit transactions are off in both versions at the server
level, thus defaulting to autocommitted mode.
Ensure sp_configure settings are identical.
Step 1: Create a DB called test:
Step 2: Execute the following under the context of test DB.
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[trigtest]') and OBJECTPROPERTY(id, Outrigger') = 1)
drop trigger [dbo].[trigtest]
GO
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[test]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[test]
GO
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[trancount]') and OBJECTPROPERTY(id, N'IsUserTable')
= 1)
drop table [dbo].[trancount]
GO
CREATE TABLE [dbo].[test] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[text] [char] (10) NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[trancount] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[trancount] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TRIGGER trigtest ON [dbo].[test]
FOR UPDATE, DELETE
AS
declare @trancount int
select @trancount = @@TRANCOUNT
insert into trancount ( trancount ) values ( @trancount )
Step 3: Run the following against the DB, then check trancount table.
-- Add a record to the test table (trigger will not fire)
insert into test (text) values ( 'xxxx' );
go
-- Update the value (autocommit mode) to fire trigger
-- Under SQL 7 and 2000, trancount table will only indicate 1
tranaction open.
-- This is being performed in autocommit mode.
update test set text = 'test1'
go
-- Update value using an explicit transaction
-- Under SQL 7, trancount will equal 2 in trigger, in SQL 2000
trancount equals 1
begin transaction
update test set text = 'test2'
commit work
go
View 5 Replies
ADVERTISEMENT
Dec 2, 2006
hi
stored procedure and trigger which runs on serverside and which runs on client side.
View 1 Replies
View Related
Jun 28, 2007
Take a look a the sql code below. Can anyone explain why @@trancount increased to 2 after the 2nd print statement?
SET ANSI_DEFAULTS ON
GO
PRINT @@TRANCOUNT
GO
BEGIN TRANSACTION
PRINT @@TRANCOUNT
GO
Here is the output I got
0
2
View 1 Replies
View Related
Apr 28, 2003
Hi,
Reviewing the MSSQL process info screen, I am seeing the same process appear a numer of times. It is always the same, being
'IF @@TRANCOUNT > 0 COMMIT TRAN'
Sometimes, there can be up to a hundred of these processes (listed in the process info screen). They generally have a 'sleeping' status, but nonetheless, I would like to see these processes disappear if they are not being used.
I have checked in all of the stored procedures and triggers in the application, and none have this sql statement.
When I run profiler, I get these entries, but the profiler says they belong to either SQL Enterprise Manager or 'Microsoft Windows 2000 Operating System', and not to the application I am running.
Does anyone know where these transactions come from? Can I prevent these from appearing? If no, what is the impact (other than sql server having to maintain a connection).
Thanks,
Jim
View 6 Replies
View Related
Sep 26, 2007
Hi all,
Is there any way to get the @@trancount for a connection from outside the connection?
The reason i'm asking is that a customer just lost a days work, and there is nothing in any table from a certain time onward. One theoy is that a backup was restored, but we checked and that is not the case.
So another theory is that a certain sproc began a transaction, but never finished because of an error. (We had some strange timeouts as well, so this is quite plausible.)
So the question: Can i get a list of current connections with their trancount? I could just run this to see if a certain connection would never get back to zero to check the transaction theory.
Thanks in advance,
Gert-Jan
View 7 Replies
View Related
Aug 2, 2006
I am creating an install program and I'm wondering if there is a
difference between SQL Server 2000 and MSDE 2000? Do they have
different entries in the Registry?
From the documentation that I've read it seems as if they are one and the same.
However, if someone knows how to differentiate between them in the Registry it would be greatly appreciated.
Thanks
View 2 Replies
View Related
Apr 19, 2005
Hi,
I am developing an web-database application using ASP.net,c# and MSDE. and after the completion of the project i want to deploy the database over the server whichs got sql server professional edition.
Are there any changes to be made while deploying it over the server and also will the connection string for MSDE and SQL client the same ?
Please do clear me the confusions i have got ..
thanks inadvance
View 2 Replies
View Related
Sep 10, 2007
Hello everyone,i want to know abt the "Difference between MSDE and SQL Server 2000". For example the features they support, capacity and requirements etc...
Reply me asap.
Thanx in Advance.
View 1 Replies
View Related
Mar 8, 2007
I found an unusual problem between 2000 and 2005 I haven't been ableto decipher from any documentation.The query structure is as follows:select *fromtableA ajointableB b ON a.somekey = b.somekeywherea.type = 'A'and datediff(yyyy, b.someDateField, getdate()) betweena.lowboundary and a.highboundarySome basic facts about the elements and data. The low and high-boundary fields are varchar datatypes. In 2005 (regardless ofcompatibility type I run the database under), the query evaluates theBETWEEN and errors out due to the fact that it is evaluating theDATEDIFF as an integer and finds a non-integer entry in eitherlowboundary or highboundary. I understand and expect this behavior.Obviously, changing the result of the DATEDIFF function to varcharallows the operation to go forth.The odd thing is that there is no "a.type = 'A' " entry, thus thequery wouldn't return anything. In 2000, it seems as though theengine is evaluating the type = 'A' and short-circuiting and in 2005,it is trying to evaluate the entire query OR is there an implicitconversion occuring in 2000 and not in 2005?As I mentioned, the compatibility mode doesn't change how this reacts,but running this on a native 2000 server allows this to happen. Thisparticular code isn't the problem, it's what we might have to contendwith when we migrate this through. Sure, we're going to performregression testing, but I'm concerned about what we would miss.Thanks for any replies.
View 2 Replies
View Related
Jan 12, 2006
I have kind of an urgent need here. I need to know if there is a dll file or registry key or something of that nature that I can query on to find out if my SQL 2000 installations are Enterprise or Standard.
I understand I can do this using query analyser, but that will not work with my reporting tool (this is for reporting numbers of SQL installations in our very large enterprise for Microsoft license compliance).
Thanks for any guidance!!
Cheryl Marland
cheryl.marland@va.gov
View 3 Replies
View Related
Aug 1, 2007
Hi,
I'm having an issue with a query I'm running on Sql Server 2005. It's a semi-complex query involving an in-line table function and several left outer joins which are joined on to the results of the function call. Two of the left outer joins are then qualified in a where clause of the form where table.Col is not null; the idea is that the final result set contains data that has no match in those two tables.
The problem revolves around a where clause in the function and the last left outer join (ie, one of the ones qualified with where not null). When I alter the where clause of the function to further restrict the result set the function returns, the query times shoots up from 1 second to roughly 2-3 minutes. Note that the time the function takes to complete is not affected. The difference in time is purely down to what the query does with the results the function provides. Also note that the change to the where clause provides a subset of the original data; it does not add any more data (it actually restricts the original resultset by roughly 1000 rows).
I can bring the query speed back down again by removing the last left outer join - this join takes one of the columns from the function, and joins it to a small table - 924 rows. So it appears that this particular join is the cause of the issue, but only when using the resultset generated from the modified function query.
Now, as the thread title alludes, Sql Server 2000 and 2005 handle this differently, or appear to. When I execute this same query on a Sql 2000 machine, there's no apparent time differences, and the data that is returned is as expected. Does anyone have any suggestions as to what might be causing this and how I can fix it? I could simply return the larger resultset and use managed code to filter out the rows I don't want; however, I would like to get to the bottom of this, especially if it's going to effect future queries.
Cheers,
Chris
View 4 Replies
View Related
Jan 9, 2006
Hi All:
I am new to Sql 2000 database,Now I'm planing to create a table in my databse,my table included below fields like this :
PoNo(the length is 15 characters) ,Supplier Name(the length is 50 characters).etc
but I don't how to select the datatype for them. should I select Char or VarChar ?
which one is the best slection ?
thans in advanced!
View 5 Replies
View Related
Oct 24, 2007
Question is in the subject.
Thanks in advance
-Jamie
View 7 Replies
View Related
Jun 18, 2007
Hello All!
I am trying to create a trigger that upon insertion into my table an email will be sent to that that recipeinent with a image attached ( like a coupon)That comes from a different table, problem is, It will not allow me to send the email ( using xp_sendmail) with the coupon attached. I am using varbinary for the coupon and nvarchar for the rest to be sent, I get an error that Invaild operator for data type. operator equals add, type equals varchar.
Looks basically like this(This is my test tables):
CREATE TRIGGER EileenTest ON OrgCouponTestMainFOR InsertAS declare @emailaddress varchar(50)declare @body varchar(300)declare @fname varchar(50)declare @coupon varbinary(4000)
if update(emailaddress)begin
Select @emailaddress=(select EmailAddress from OrgCouponTestMain as str), @fname=(select EmailAddress from OrgCouponTestMain as str) @Coupon=(select OrgCoupon1 from OrgCouponTest2 as image)
SET @body= 'Thank you' +' '+ @fname +' '+ ',Here is the coupon you requested' +' ' + @couponexec master.dbo.xp_sendmail @recipients = @emailaddress, @subject = 'Coupon', @message = @bodyEND
View 6 Replies
View Related
Apr 3, 2006
Database Layout: Database 1 Contains table called “dbo.Users� Users table contains field/column “Username�. Database 2 Contains table called “dbo.aspnet_Users� Aspnet_Users contains field/column “UserName� Problem: Whenever a record’s “Username� field is updated in dbo.Users (Database 1), I need to update the “UserName� field in aspnet_Users (Database 2). How should I write the trigger to accomplish this task? The following trigger is currently_not_ working. :(ALTER TRIGGER [trig_updateUserNameForForum] ON [dbo].[Users] FOR UPDATE AS DECLARE @oldUserName NVARCHAR(256) DECLARE @newUserName NVARCHAR(256) IF UPDATE(Username) BEGIN SELECT @oldUserName = (SELECT Username FROM Deleted) SELECT @newUserName = (SELECT Username FROM Inserted) UPDATE Database2.dbo.aspnet_Users SET Username = @newUsername WHERE UserName = @oldUserName RETURN END Thanks!!! -Cody
View 22 Replies
View Related
Jan 30, 2008
How can I fire a procedure when a field is less than a threshold in sql server 2000?
Have you got any idea or suggestion?
Thanks in advance,
Andrea
View 1 Replies
View Related
Jan 19, 2007
I have a trigger that should be execute on each row insert and only ifappcode = 'I' and datasent = 0. It should execute a DTS package. TheDTS package by itself runs about 6 seconds. Trigger was createdsuccessfuly. When I try to insert a row my db hangs. I can see thatSPID on my db is hang by SPID from master db. It doesn't completeuntil I kill that SPID. Why is that?This is the trigger that I am trying to execute:CREATE TRIGGER myExportON ruExportFOR INSERTASdeclare @appcode varchar (10)select @appcode = appcode from ruexport where appcode = 'I' anddatesent = 0if @appcode = 'I'exec master..xp_cmdshell 'DTSRun /S "KOCL384017SQL" /N "Sys_Export" /G"{17D112A8-413E-420F-A624-3790BDFBED9F}" /W "0" /E'goAny suggestions?
View 2 Replies
View Related
Jul 20, 2005
Hi,can someone tell how to write a Trigger; I am familiar with Sybase SqlAnywhere trigger syntax.Actually I have three tables MEMBER, CONTRACT and PAYMENTI need to update the MEMBER.BALANCE once the PAYMENT.AMOUNT is INSERTEDwhere PAYEMENT.CONTRAC_ID = CONTRACT.CONTRAC_IDand CONTRAT.MEMBER_ID = MEMBRE.MEMBER_IDI have more TRIGGERS to write, but with a good example it would be greatIn fact, send me as many examples as you canThanksFernandJoin Bytes!
View 9 Replies
View Related
Mar 3, 2006
What are the difference between SQL Server 2000 and SQL Server 2005 Express Edition.?
Or where i can find the list of differences. ?
Can SQL Server 2000 and SQL Server 2005 Express Edition can be used interchangeably for basic database operations?
Hope to get some response soon.
Regards
Sanjeev
View 2 Replies
View Related
Jul 20, 2005
Hi Everyone,Apparently, I was being asked on a question, "Why don't we procure adesktop PC to run MS SQL Server 2000 rather than a buying a server?".From a Management point-of-view, buying a desktop PC is much cheaperthan a server. However, I just wanted to understand that is it aviable solution given the database size is something around 200 GB?Equipping with more memory, more storage and a more powerful CPU on adesktop PC could really taking up the role to support the DBMS?Besides this "sensitive" costing concerns, what will be othersdifference in running the SQL Server 2000 on the two differenthardware architecture? For example, IO rate, reliability, RAID-1support, performance, … etc.(Note: The operating system is Microsoft Windows 2000 EnterpriseEdition)Regards,Ambrose
View 1 Replies
View Related
Sep 18, 2001
Hi Iam trying to do a trigger that everytime I Update a record de date get update too I finally find a trigger close to that, but this trigger update all the dates from all the record of the same table I wonder is there are a way that I can do it by the date of the record, if somebody could help I will really appreciate.
Thi is the trigger that I have so far
Create Trigger Update_Date
on DBO.Company After Update as
Update dbo.Company
Set ActualiizationDate=Getdate()
go
View 1 Replies
View Related
Aug 3, 2006
Dear Freinds,
we are having an requirement to log the unauthorized backend update on database.Is there any other way ,apart from going and creating the triggers at each table to log the backend update.
Note :Is Database base level trigger is possible on SQL Server 2000?
Looking for your reply.
With Cheers :beer: ,
Sathesh.M
View 3 Replies
View Related
Nov 28, 2007
Hi all,
I have a trigger for column eISBNEnteredDate on update or insert changes of eISBN of the table Products2 ( both belong to the same table). The column eISBNEnteredDate can either be added manually along with eISBN value or when only eISBN value is entered it is updated with present date.
The problem I am facing is when I send eISBN along with eISBNEnteredDate the present date is what is getting saved. Upon the same record when a new date is updated the new date is getting saved. Can someone tell me where I am going wrong?
Here is my trigger:
Code Block
ALTER TRIGGER [dbo].[Products2_eISBNEnteredDate] ON [dbo].[Products2]
For Insert, Update
As
Begin
Declare @ProductId int
Declare @eISBN Varchar(17)
Set @eISBN = '0'
If ( Update(eISBN) )
Begin
Select @Productid = I.Productid,@eISBN = I.eISBN
From Inserted I Left Join Deleted d on I.Productid = D.Productid
Left join Products2 P on P.Productid = I.Productid
Where (ISNULL(I.eISBN,'') <> ISNULL(D.eISBN,''))
If (IsNull(@eISBN,'') <> '' and IsNull(@eISBN,'') <> '0')
Begin
Update Products2
Set eISBNEnteredDate = getdate()
Where ProductID in (select i.ProductID
From Inserted i
Left join Deleted d on d.ProductID = i.ProductID
Where (i.eISBN is not null or replace(i.eISBN,' ','') != '') --where the new eISBN is not null or blank
and (d.eISBN is null or replace(d.eISBN,' ','') = '') --where the old eISBN is null or blank
and isnull(i.eISBN,'') != isnull(d.eISBN,'') --where the new eISBN is not equal to the old ISBN13
and d.eISBNEnteredDate is null)
End
If IsNull(@eISBN,'') = '' and IsNull(@eISBN,'') = ''
Begin
Update Products2
set eISBNEnteredDate = NULL
Where ProductID = @Productid
End
End
End
View 5 Replies
View Related
Jul 23, 2005
Hi -We have two SQL 2000 Servers. We have the linked server setup and wecan perform updates and inserts between the databases. But when we adda trigger and insert something into a table, the database hangs. Thereare NO processes blocking or being block in either database. This ONLYoccurs when we have one OS as Windows 2000 Server and the other OS asWindows 2003 Server. This problem does not occur when both servers areWindows 2000. Has anyone ran into anything similar to this???*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!
View 2 Replies
View Related
Jul 20, 2005
Hi All,I'm a relatively newbie to SQL Server 2000, having come from a MySQLbackground.I'm creating my first Trigger statement on a table, and I'd like toknow how I go about performing an update on the row that was changedwhen the trigger was fired.To explain, I have 2 columns, one which contains a member number, theother which contains a flag that is supposed to indicate whether ornot the member number in the row has changed since the last time thetable was processed for updates.So, whenever the value in the member number field [memnum] is updated,I want to set the flag [igproc] to true.The best I've been able to do is:CREATE TRIGGER [updateignoreprocflag] ON [dbo].[dd_testtable]FOR UPDATEASdeclare @key as intIF UPDATE (memnum)select @key = recid from insertedUPDATE dd_testtable set igproc=1 where recid=@keyThis seems to work, but I'd like to know if there's a better way ofretrieving the recid value of the changed row to pass to the UPDATEstatement? Also, I read somewhere in passing that using SELECTstatements and variable assignments within triggers can cause problemswhen called from other applications; in this case it will either be aweb site using ASP.or an application developed in FOXPRO. I can't findwhere I read this originally, so it's entirely possible I imagined itor misunderstood it, but I'd very much appreciate it if someone couldconfirm whether or not this is the case?Many, many thanks in advance!Much warmth,Murray
View 2 Replies
View Related
Jan 17, 2008
Hi
Can u please send the answers for this
1 . Can write more than one trigger for a single table(sql server 2000)?
2. how to create the editable gridview? While clicking particular cell it should be changed to
Edit mode , and I want option for creating new row and delete option, search option
View 1 Replies
View Related
Nov 14, 2006
Hey,
I'm new to this whole SQL Server 2005 thing as well as database design and I've read up on various ways I can integrate business constraints into my database. I'm not sure which way applies to me, but I could use a helping hand in the right direction.
A quick explanation of the various tables I'm dealing with:
WBS - the Work Breakdown Structure, for example: A - Widget 1, AA - Widget 1 Subsystem 1, and etc.
Impacts - the Risk or Opportunity impacts for the weights of a part/assembly. (See Assemblies have Impacts below)
Allocations - the review of the product in question, say Widget 1, in terms of various weight totals, including all parts. Example - September allocation, Initial Demo allocation, etc. Mostly used for weight history and trending
Parts - There are hundreds of Parts which will eventually lead to thousands. Each part has a WBS element. [Seems redundant, but parts are managed in-house, and WBS elements are cross-company and issued by the Government]
Parts have Allocations - For weight history and trending (see Allocations). Example, Nut 17 can have a September 1st allocation, a September 5th allocation, etc.
Assemblies - Parts are assemblies by themselves and can belong to multiple assemblies. Now, there can be multiple parts on a product, say, an unmanned ground vehicle (UGV), and so those parts can belong to a higher "assembly" [For example, there can be 3 Nut 17's (lower assembly) on Widget 1 Subsystem 2 (higher assembly) and 4 more on Widget 1 Subsystem 5, etc.]. What I'm concerned about is ensuring that the weight roll-ups are accurate for all of the assemblies.
Assemblies have Impacts - There is a risk and opportunity impact setup modeled into this design to allow for a risk or opportunity to be marked on a per-assembly level. That's all this table represents.
A part is allocated a weight and then assigned to an assembly. The Assemblies table holds this hierarchical information - the lower assembly and the higher one, both of which are Parts entries in the [Parts have Allocations] table.
Therefore, to ensure proper weight roll ups in the [Parts have Allocations] table on a per part-basis, I would like to check for any inserts, updates, deletes on both the [Parts have Allocations] table as well as the [Assemblies] table and then re-calculate the weight roll up for every assembly. Now, I'm not sure if this is a huge performance hog, but I do need to keep all the information as up-to-date and as accurate as possible. As such, I'm not sure which method is even correct, although it seems an AFTER DML trigger is in order (from what I've gathered thus far). Keep in mind, this trigger needs to go through and check every WBS or Part and then go through and check all of it's associated assemblies and then ensure the weights are correct by re-summing the weights listed.
If you need the design or create script (table layout), please let me know.
Thanks.
View 4 Replies
View Related
Jul 20, 2005
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 1 Replies
View Related
Dec 5, 2006
This Audit Trigger is Generic (i.e. non-"Table Specific") attach it to any tabel and it should work. Be sure and create the 'Audit' table first though.
The following code write audit entries to a Table called
'Audit'
with columns
'ActionType' //varchar
'TableName' //varchar
'PK' //varchar
'FieldName' //varchar
'OldValue' //varchar
'NewValue' //varchar
'ChangeDateTime' //datetime
'ChangeBy' //varchar
using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
public partial class Triggers
{
//A Generic Trigger for Insert, Update and Delete Actions on any Table
[Microsoft.SqlServer.Server.SqlTrigger(Name = "AuditTrigger", Event = "FOR INSERT, UPDATE, DELETE")]
public static void AuditTrigger()
{
SqlTriggerContext tcontext = SqlContext.TriggerContext; //Trigger Context
string TName; //Where we store the Altered Table's Name
string User; //Where we will store the Database Username
DataRow iRow; //DataRow to hold the inserted values
DataRow dRow; //DataRow to how the deleted/overwritten values
DataRow aRow; //Audit DataRow to build our Audit entry with
string PKString; //Will temporarily store the Primary Key Column Names and Values here
using (SqlConnection conn = new SqlConnection("context connection=true"))//Our Connection
{
conn.Open();//Open the Connection
//Build the AuditAdapter and Mathcing Table
SqlDataAdapter AuditAdapter = new SqlDataAdapter("SELECT * FROM Audit WHERE 1=0", conn);
DataTable AuditTable = new DataTable();
AuditAdapter.FillSchema(AuditTable, SchemaType.Source);
SqlCommandBuilder AuditCommandBuilder = new SqlCommandBuilder(AuditAdapter);//Populates the Insert command for us
//Get the inserted values
SqlDataAdapter Loader = new SqlDataAdapter("SELECT * from INSERTED", conn);
DataTable inserted = new DataTable();
Loader.Fill(inserted);
//Get the deleted and/or overwritten values
Loader.SelectCommand.CommandText = "SELECT * from DELETED";
DataTable deleted = new DataTable();
Loader.Fill(deleted);
//Retrieve the Name of the Table that currently has a lock from the executing command(i.e. the one that caused this trigger to fire)
SqlCommand cmd = new SqlCommand("SELECT object_name(resource_associated_entity_id) FROM
ys.dm_tran_locks WHERE request_session_id = @@spid and resource_type = 'OBJECT'", conn);
TName = cmd.ExecuteScalar().ToString();
//Retrieve the UserName of the current Database User
SqlCommand curUserCommand = new SqlCommand("SELECT system_user", conn);
User = curUserCommand.ExecuteScalar().ToString();
//Adapted the following command from a T-SQL audit trigger by Nigel Rivett
//http://www.nigelrivett.net/AuditTrailTrigger.html
SqlDataAdapter PKTableAdapter = new SqlDataAdapter(@"SELECT c.COLUMN_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
where pk.TABLE_NAME = '" + TName + @"'
and CONSTRAINT_TYPE = 'PRIMARY KEY'
and c.TABLE_NAME = pk.TABLE_NAME
and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME", conn);
DataTable PKTable = new DataTable();
PKTableAdapter.Fill(PKTable);
switch (tcontext.TriggerAction)//Switch on the Action occuring on the Table
{
case TriggerAction.Update:
iRow = inserted.Rows[0];//Get the inserted values in row form
dRow = deleted.Rows[0];//Get the overwritten values in row form
PKString = PKStringBuilder(PKTable, iRow);//the the Primary Keys and There values as a string
foreach (DataColumn column in inserted.Columns)//Walk through all possible Table Columns
{
if (!iRow[column.Ordinal].Equals(dRow[column.Ordinal]))//If value changed
{
//Build an Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "U";//U for Update
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = dRow[column.Ordinal].ToString();
aRow["NewValue"] = iRow[column.Ordinal].ToString();
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the entry
}
}
break;
case TriggerAction.Insert:
iRow = inserted.Rows[0];
PKString = PKStringBuilder(PKTable, iRow);
foreach (DataColumn column in inserted.Columns)
{
//Build an Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "I";//I for Insert
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = null;
aRow["NewValue"] = iRow[column.Ordinal].ToString();
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the Entry
}
break;
case TriggerAction.Delete:
dRow = deleted.Rows[0];
PKString = PKStringBuilder(PKTable, dRow);
foreach (DataColumn column in inserted.Columns)
{
//Build and Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "D";//D for Delete
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = dRow[column.Ordinal].ToString();
aRow["NewValue"] = null;
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the Entry
}
break;
default:
//Do Nothing
break;
}
AuditAdapter.Update(AuditTable);//Write all Audit Entries back to AuditTable
conn.Close(); //Close the Connection
}
}
//Helper function that takes a Table of the Primary Key Column Names and the modified rows Values
//and builds a string of the form "<PKColumn1Name=Value1>,PKColumn2Name=Value2>,......"
public static string PKStringBuilder(DataTable primaryKeysTable, DataRow valuesDataRow)
{
string temp = String.Empty;
foreach (DataRow kColumn in primaryKeysTable.Rows)//for all Primary Keys of the Table that is being changed
{
temp = String.Concat(temp, String.Concat("<", kColumn[0].ToString(), "=", valuesDataRow[kColumn[0].ToString)].ToString(), ">,"));
}
return temp;
}
}
The trick was getting the Table Name and the Primary Key Columns.
I hope this code is found useful.
Comments and Suggestion will be much appreciated.
View 16 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
Mar 18, 2008
how to create new CLR trigger from existing T-Sql Trigger Thanks in advance
View 3 Replies
View Related
Jul 23, 2005
When a row gets modified and it invokes a trigger, we would like to beable to update the row that was modified inside the trigger. This is(basically) how we are doing it now:CREATE TRIGGER trTBL ON TBLFOR UPDATE, INSERT, DELETEasupdate TBLset fld = 'value'from inserted, TBLwhere inserted.id= TBL.id....This work fine but it seems like it could be optimized. Clearly we arehaving to scan the entire table again to update the row. But shouldn'tthe trigger already know which row invoked it. Do we have to scan thetable again for this row or is their some syntax that allows us toupdate the row that invoked the trigger. If not, why. It seems likethis would be a fairly common task. Thanks.
View 4 Replies
View Related