473,703 Members | 2,958 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SQL Trigger for changed columns?

I have never written a trigger before and now am seeing the light. Is
there a way to write a trigger so that if a user changes any column in
a single row on one table then the trigger will write the value of
this (these) rows to a second table. I don't want the unchanged
columns, just the changed columns (with column names...)
Thanks,
lq
Jul 20 '05 #1
10 39492
On 12 Apr 2004 18:36:24 -0700, Lauren Quantrell wrote:
I have never written a trigger before and now am seeing the light. Is
there a way to write a trigger so that if a user changes any column in
a single row on one table then the trigger will write the value of
this (these) rows to a second table. I don't want the unchanged
columns, just the changed columns (with column names...)
Thanks,
lq


Something like this, maybe?

CREATE TABLE Lauren
(KeyCol int not null primary key,
DataCol1 int not null,
DataCol2 int null,
DataCol3 int not null)
go
CREATE TABLE Quantrell
(KeyCol int not null primary key,
ColName char(8) not null,
NewData int not null)
go

CREATE TRIGGER LaurenQuantrell
ON Lauren AFTER UPDATE
AS
IF UPDATE(KeyCol)
BEGIN
RAISERROR ('Don't change the key column!!', 16, 1)
ROLLBACK TRANSACTION
RETURN
END

INSERT Quantrell (KeyCol, ColName, NewData)
SELECT inserted.KeyCol , 'DataCol1', inserted.DataCo l1
FROM inserted
INNER JOIN deleted ON deleted.KeyCol = inserted.KeyCol
WHERE inserted.DataCo l1 <> deleted.DataCol 1

INSERT Quantrell (KeyCol, ColName, NewData)
SELECT inserted.KeyCol , 'DataCol2', inserted.DataCo l1
FROM inserted
INNER JOIN deleted ON deleted.KeyCol = inserted.KeyCol
WHERE inserted.DataCo l2 <> deleted.DataCol 2
OR (inserted.DataC ol2 IS NULL AND deleted.DataCol 2 IS NOT NULL)
OR (inserted.DataC ol2 IS NOT NULL AND deleted.DataCol 2 IS NULL)

INSERT Quantrell (KeyCol, ColName, NewData)
SELECT inserted.KeyCol , 'DataCol3', inserted.DataCo l3
FROM inserted
INNER JOIN deleted ON deleted.KeyCol = inserted.KeyCol
WHERE inserted.DataCo l3 <> deleted.DataCol 3
go
Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 20 '05 #2
On 12 Apr 2004 18:36:24 -0700, Lauren Quantrell wrote:
I have never written a trigger before and now am seeing the light. Is
there a way to write a trigger so that if a user changes any column in
a single row on one table then the trigger will write the value of
this (these) rows to a second table. I don't want the unchanged
columns, just the changed columns (with column names...)
Thanks,
lq


Something like this, maybe?

CREATE TABLE Lauren
(KeyCol int not null primary key,
DataCol1 int not null,
DataCol2 int null,
DataCol3 int not null)
go
CREATE TABLE Quantrell
(KeyCol int not null primary key,
ColName char(8) not null,
NewData int not null)
go

CREATE TRIGGER LaurenQuantrell
ON Lauren AFTER UPDATE
AS
IF UPDATE(KeyCol)
BEGIN
RAISERROR ('Don't change the key column!!', 16, 1)
ROLLBACK TRANSACTION
RETURN
END

INSERT Quantrell (KeyCol, ColName, NewData)
SELECT inserted.KeyCol , 'DataCol1', inserted.DataCo l1
FROM inserted
INNER JOIN deleted ON deleted.KeyCol = inserted.KeyCol
WHERE inserted.DataCo l1 <> deleted.DataCol 1

INSERT Quantrell (KeyCol, ColName, NewData)
SELECT inserted.KeyCol , 'DataCol2', inserted.DataCo l1
FROM inserted
INNER JOIN deleted ON deleted.KeyCol = inserted.KeyCol
WHERE inserted.DataCo l2 <> deleted.DataCol 2
OR (inserted.DataC ol2 IS NULL AND deleted.DataCol 2 IS NOT NULL)
OR (inserted.DataC ol2 IS NOT NULL AND deleted.DataCol 2 IS NULL)

INSERT Quantrell (KeyCol, ColName, NewData)
SELECT inserted.KeyCol , 'DataCol3', inserted.DataCo l3
FROM inserted
INNER JOIN deleted ON deleted.KeyCol = inserted.KeyCol
WHERE inserted.DataCo l3 <> deleted.DataCol 3
go
Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 20 '05 #3
Hugo,
Thanks for that code!
Now, the rub is that all the columns are integer types. I've got
ntext, nvarchar, int, smallint, tinyint...
lq

Hugo Kornelis <hugo@pe_NO_rFa ct.in_SPAM_fo> wrote in message news:<e6******* *************** **********@4ax. com>...
On 12 Apr 2004 18:36:24 -0700, Lauren Quantrell wrote:
I have never written a trigger before and now am seeing the light. Is
there a way to write a trigger so that if a user changes any column in
a single row on one table then the trigger will write the value of
this (these) rows to a second table. I don't want the unchanged
columns, just the changed columns (with column names...)
Thanks,
lq


Something like this, maybe?

CREATE TABLE Lauren
(KeyCol int not null primary key,
DataCol1 int not null,
DataCol2 int null,
DataCol3 int not null)
go
CREATE TABLE Quantrell
(KeyCol int not null primary key,
ColName char(8) not null,
NewData int not null)
go

CREATE TRIGGER LaurenQuantrell
ON Lauren AFTER UPDATE
AS
IF UPDATE(KeyCol)
BEGIN
RAISERROR ('Don't change the key column!!', 16, 1)
ROLLBACK TRANSACTION
RETURN
END

INSERT Quantrell (KeyCol, ColName, NewData)
SELECT inserted.KeyCol , 'DataCol1', inserted.DataCo l1
FROM inserted
INNER JOIN deleted ON deleted.KeyCol = inserted.KeyCol
WHERE inserted.DataCo l1 <> deleted.DataCol 1

INSERT Quantrell (KeyCol, ColName, NewData)
SELECT inserted.KeyCol , 'DataCol2', inserted.DataCo l1
FROM inserted
INNER JOIN deleted ON deleted.KeyCol = inserted.KeyCol
WHERE inserted.DataCo l2 <> deleted.DataCol 2
OR (inserted.DataC ol2 IS NULL AND deleted.DataCol 2 IS NOT NULL)
OR (inserted.DataC ol2 IS NOT NULL AND deleted.DataCol 2 IS NULL)

INSERT Quantrell (KeyCol, ColName, NewData)
SELECT inserted.KeyCol , 'DataCol3', inserted.DataCo l3
FROM inserted
INNER JOIN deleted ON deleted.KeyCol = inserted.KeyCol
WHERE inserted.DataCo l3 <> deleted.DataCol 3
go
Best, Hugo

Jul 20 '05 #4
On 14 Apr 2004 16:13:37 -0700, Lauren Quantrell wrote:
Hugo,
Thanks for that code!
Now, the rub is that all the columns are integer types. I've got
ntext, nvarchar, int, smallint, tinyint...
lq


Hi Lauren,

If you need the data in the second table for audit purposes, then this
might be one of the very rare cases where datatype sql_variant can be
used. Check Books Online for details on this datatype and see if it
can be used in your situation.

I the second table is not for audit, then it might well be worth to
consider the design of this table. If you can explain what business
problem you have to solve, I can try if I can find a better solution.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 20 '05 #5
Hugo,
Thanks for that code!
Now, the rub is that all the columns are integer types. I've got
ntext, nvarchar, int, smallint, tinyint...
lq

Hugo Kornelis <hugo@pe_NO_rFa ct.in_SPAM_fo> wrote in message news:<e6******* *************** **********@4ax. com>...
On 12 Apr 2004 18:36:24 -0700, Lauren Quantrell wrote:
I have never written a trigger before and now am seeing the light. Is
there a way to write a trigger so that if a user changes any column in
a single row on one table then the trigger will write the value of
this (these) rows to a second table. I don't want the unchanged
columns, just the changed columns (with column names...)
Thanks,
lq


Something like this, maybe?

CREATE TABLE Lauren
(KeyCol int not null primary key,
DataCol1 int not null,
DataCol2 int null,
DataCol3 int not null)
go
CREATE TABLE Quantrell
(KeyCol int not null primary key,
ColName char(8) not null,
NewData int not null)
go

CREATE TRIGGER LaurenQuantrell
ON Lauren AFTER UPDATE
AS
IF UPDATE(KeyCol)
BEGIN
RAISERROR ('Don't change the key column!!', 16, 1)
ROLLBACK TRANSACTION
RETURN
END

INSERT Quantrell (KeyCol, ColName, NewData)
SELECT inserted.KeyCol , 'DataCol1', inserted.DataCo l1
FROM inserted
INNER JOIN deleted ON deleted.KeyCol = inserted.KeyCol
WHERE inserted.DataCo l1 <> deleted.DataCol 1

INSERT Quantrell (KeyCol, ColName, NewData)
SELECT inserted.KeyCol , 'DataCol2', inserted.DataCo l1
FROM inserted
INNER JOIN deleted ON deleted.KeyCol = inserted.KeyCol
WHERE inserted.DataCo l2 <> deleted.DataCol 2
OR (inserted.DataC ol2 IS NULL AND deleted.DataCol 2 IS NOT NULL)
OR (inserted.DataC ol2 IS NOT NULL AND deleted.DataCol 2 IS NULL)

INSERT Quantrell (KeyCol, ColName, NewData)
SELECT inserted.KeyCol , 'DataCol3', inserted.DataCo l3
FROM inserted
INNER JOIN deleted ON deleted.KeyCol = inserted.KeyCol
WHERE inserted.DataCo l3 <> deleted.DataCol 3
go
Best, Hugo

Jul 20 '05 #6
On 14 Apr 2004 16:13:37 -0700, Lauren Quantrell wrote:
Hugo,
Thanks for that code!
Now, the rub is that all the columns are integer types. I've got
ntext, nvarchar, int, smallint, tinyint...
lq


Hi Lauren,

If you need the data in the second table for audit purposes, then this
might be one of the very rare cases where datatype sql_variant can be
used. Check Books Online for details on this datatype and see if it
can be used in your situation.

I the second table is not for audit, then it might well be worth to
consider the design of this table. If you can explain what business
problem you have to solve, I can try if I can find a better solution.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 20 '05 #7
Hugo,
Thanks for your replies and your help.
I'm trying to keep a record of every change a user makes to any field
on a form.
The underlying recordsource is an SP that refers to a single table.
The user can only modify one row at a time.

Ideally, I would track changes to datetime, int, nvarchar and ntext
columns.
This is used entirely as an audit trail, but users would be able to
click a button to view the changes any user had made.

The table holding the audit would need a column for the fieldname
nvarchar(25), databeforechang e (?), dataafterchange (?), userID int,
dateofchange smalldatetime.

This must be a pretty common need?

lq

Hugo Kornelis <hugo@pe_NO_rFa ct.in_SPAM_fo> wrote in message news:<pn******* *************** **********@4ax. com>...
On 14 Apr 2004 16:13:37 -0700, Lauren Quantrell wrote:
Hugo,
Thanks for that code!
Now, the rub is that all the columns are integer types. I've got
ntext, nvarchar, int, smallint, tinyint...
lq


Hi Lauren,

If you need the data in the second table for audit purposes, then this
might be one of the very rare cases where datatype sql_variant can be
used. Check Books Online for details on this datatype and see if it
can be used in your situation.

I the second table is not for audit, then it might well be worth to
consider the design of this table. If you can explain what business
problem you have to solve, I can try if I can find a better solution.

Best, Hugo

Jul 20 '05 #8
On 15 Apr 2004 15:49:24 -0700, Lauren Quantrell wrote:
Hugo,
Thanks for your replies and your help.
I'm trying to keep a record of every change a user makes to any field
on a form.
The underlying recordsource is an SP that refers to a single table.
The user can only modify one row at a time.

Ideally, I would track changes to datetime, int, nvarchar and ntext
columns.
This is used entirely as an audit trail, but users would be able to
click a button to view the changes any user had made.

The table holding the audit would need a column for the fieldname
nvarchar(25) , databeforechang e (?), dataafterchange (?), userID int,
dateofchange smalldatetime.

This must be a pretty common need?

lq


Hi Lauren,

The need is pretty common indeed. But you have chosen an approach that
differs from how I normally solve this.

I prefer to make an audit table with the same rows as the actual data
table (but all except the key columns nullable), plus extra rows (not
nullable) for userid, time of change, etc. PK of this table is equal
to the PK of the actual data table plus time of change.

Then, I make the following triggers:
* One trigger for insert, update that enters all "new" information
(from the inserted pseudo-table) into the audit table
* One trigger for delete that enters just the key columns into the
audit table. If all non-key columns in the actual data table are
nullable, you'll also need a "deleted" indication to see the
difference between a deletion and an update that sets all non-key
columns to null.

Advantage of this approach is that you have all information at a
glance, the triggers are easy to set up and will also work when
set-based changes are carried out on the data and it saves some space
if changes usually affect multiple columns at the same time.

Disadvantage is that your approach costs less space if changes usually
affect only one or two columns. That being said, I'd still choose "my"
approach even if it costs more disk space - I value ease of use and
maintainability more than disk space.

(Note - the ntext columns might require special handling, in both
scenario's. In "your" version because a sql_variant datatype can't be
used to hold ntext (if I recall correctly); in "my" version because it
might be worthwile to exclude this column from the audit table if the
text is rarely changed. Besides, I don't know how ntext data is
handled in triggers and if all set-based operations are allowed on
ntext data)

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 20 '05 #9
Hugo,
Thanks for your replies and your help.
I'm trying to keep a record of every change a user makes to any field
on a form.
The underlying recordsource is an SP that refers to a single table.
The user can only modify one row at a time.

Ideally, I would track changes to datetime, int, nvarchar and ntext
columns.
This is used entirely as an audit trail, but users would be able to
click a button to view the changes any user had made.

The table holding the audit would need a column for the fieldname
nvarchar(25), databeforechang e (?), dataafterchange (?), userID int,
dateofchange smalldatetime.

This must be a pretty common need?

lq

Hugo Kornelis <hugo@pe_NO_rFa ct.in_SPAM_fo> wrote in message news:<pn******* *************** **********@4ax. com>...
On 14 Apr 2004 16:13:37 -0700, Lauren Quantrell wrote:
Hugo,
Thanks for that code!
Now, the rub is that all the columns are integer types. I've got
ntext, nvarchar, int, smallint, tinyint...
lq


Hi Lauren,

If you need the data in the second table for audit purposes, then this
might be one of the very rare cases where datatype sql_variant can be
used. Check Books Online for details on this datatype and see if it
can be used in your situation.

I the second table is not for audit, then it might well be worth to
consider the design of this table. If you can explain what business
problem you have to solve, I can try if I can find a better solution.

Best, Hugo

Jul 20 '05 #10

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

Similar topics

2
4196
by: Trevor Fairchild | last post by:
I am trying to create a very minimal auditing system for a series of databases. I am in the process of writing Update triggers for 5 Tablse. I will write a trigger for each table-the trigger's function will be to INSERT a row into my MasterChanges table everytime ANY data is changed in each of the 5 tables. I have set up MasterChanges to capture the following: what Table the change was made in
1
7233
by: Rebecca Lovelace | last post by:
I have a trigger on a table. I am trying to dynamically log the changed fields on the table to another table, so I am iterating through the bits in COLUMNS_UPDATED() to find what's changed, and getting the column name programatically. This is all working fine. If I do a regular insert command in my trigger then everything works fine. However, since I want to retrieve data from the column name which I got programatically from the...
2
10631
by: M Wells | last post by:
Hi All, I'm a relatively newbie to SQL Server 2000, having come from a MySQL background. I'm creating my first Trigger statement on a table, and I'd like to know how I go about performing an update on the row that was changed when the trigger was fired. To explain, I have 2 columns, one which contains a member number, the
3
7280
by: takilroy | last post by:
Hi, Does anyone know of a simple way to do this? I want to create an insert trigger for a table and if the record already exists based on some criteria, I want to update the table with the values that are passed in via the insert trigger without having to use all the 'set' statements for each field (so if we add fields in the future I won't have to update the trigger). In other words, I want the trigger code to look something like...
1
3537
by: Tolga Yaramis via SQLMonster.com | last post by:
Hi All I have a question about generating dynmamicly If Update() statement in a trigger.. in My db, there is a table that holds some column names of an another table. for example; Columns Table-A: Col1, Col2, Col3, Col4,Col5
4
3647
by: Josué Maldonado | last post by:
Hello list, First of all, excuse me if this is not the right place to ask my question. Is there a way in postgresql to loop to all the fields of a given table and compare the OLD and NEW value for each field. I need to make an audit table that must contain only the fields changed after and insert/update. Thanks in advance
3
4306
by: Justin Clift | last post by:
Hi all, I'm creating a centralised table to keep a log of changes in other tables. In thinking about the PL/pgSQL trigger to write and attach to the monitored tables (probably a row level AFTER trigger), I can see two approaches: a) Write a separate PL/pgSQL function for each table, with the hard coded field names in the function.
5
5357
by: wpellett | last post by:
I can not get the SQL compiler to rewrite my SQL UPDATE statement to include columns being SET in a Stored Procedure being called from a BEFORE UPDATE trigger. Example: create table schema1.emp ( fname varchar(15) not null, lname varchar(15) not null, dob date,
1
2588
parshupooja
by: parshupooja | last post by:
Hey All, I have table A which has 20 columns. I want to create trigger on table A which should get triggered whenever someone tries to update any value in Table A than trigger should insert new as well old value in table B. For ex: Table B PK Oldvalue NewValue 1 Brown Blonde I don't want to insert all columns values instead I want to know what specific column has been changed. if two values are...
0
8763
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8676
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9266
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...
1
9020
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7878
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6602
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
4692
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3128
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
2467
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.