473,412 Members | 2,239 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,412 software developers and data experts.

instead of trigger example

joe
hi i am trying to write a insted of insert trigger to
create a unique id when i insert a record in my database.
can anyone give me an example with out using identity. thanks
Jul 20 '05 #1
8 8752
A few questions:

How will the ID be generated? And have you thought about how you will
ensure uniqueness without locking the entire table each time? This will
incur a severe performance penalty. But perhaps that doesn't matter in your
app.

Anyway, what's wrong with using IDENTITY for your needs, or at least to
assist?
"joe" <jc*****@hotmail.com> wrote in message
news:Xn*****************************@207.69.154.20 2...
hi i am trying to write a insted of insert trigger to
create a unique id when i insert a record in my database.
can anyone give me an example with out using identity. thanks

Jul 20 '05 #2
joe
i just read an article on google that talked about using instead of
triggers so i was a little bet puzzled. but i got it to work
i bet it needs locking but here is the code

CREATE TABLE table1 (

pk int NOT NULL ,

flag int NULL

)
create function maxpk()

returns int

as

BEGIN

DECLARE @qty INT

SELECT @qty = 0

select @qty=max(pk)+1 from table1

return ISNULL(@qty, 0)

END

CREATE TRIGGER tr_test ON table1

INSTEAD OF INSERT

AS BEGIN

INSERT INTO table1(pk,flag)

select dbo.maxpk(), flag from inserted

END
Jul 20 '05 #3
Does this code actually work for you? When I try an insert, I get the
error:

The column 'pk' in table 'table1' cannot be null.

If I make 'pk' nullable, another problem is exposed, that of multi-row
INSERTs; try this:

insert table1 (flag)
select 1
union all
select 1

You'll need a loop in the trigger to get rid of that problem, I believe.
"joe" <jc*****@hotmail.com> wrote in message
news:Xn*****************************@207.69.154.20 2...
i just read an article on google that talked about using instead of
triggers so i was a little bet puzzled. but i got it to work

Jul 20 '05 #4
joe (jc*****@hotmail.com) writes:
i just read an article on google that talked about using instead of
triggers so i was a little bet puzzled. but i got it to work
i bet it needs locking but here is the code

CREATE TABLE table1 (
pk int NOT NULL ,
flag int NULL
)
create function maxpk() returns int as
BEGIN
DECLARE @qty INT
SELECT @qty = 0
select @qty=max(pk)+1 from table1
return ISNULL(@qty, 0)
END

CREATE TRIGGER tr_test ON table1
INSTEAD OF INSERT
AS BEGIN
INSERT INTO table1(pk,flag)
select dbo.maxpk(), flag from inserted
END


Unfortunately, this won't fly well. It works if you insert one row at
a time, but as Adam pointed out, it fails for multi-row inserts. Also,
calling a user-defined function for each is bad for performance, because
the scalar UDF converts the statement to a cursor behind the scenes.
Again, this does not matter for a single-row insert, but if you insert
10000 rows, it will cost you dearly.

The simplest solution for this is to use - IDENTITY. But not on the
target table itself. Here's how you do it:
CREATE TABLE table1 (
pk int NOT NULL
CONSTRAINT default_pk DEFAULT 0,
flag int NULL,
CONSTRAINT pk_table1 PRIMARY KEY (pk)
)
go
CREATE TRIGGER tritest ON table1 INSTEAD OF INSERT AS

DECLARE @temp TABLE (ident int IDENTITY PRIMARY KEY,
flag int NULL)

DECLARE @maxpk int

INSERT @temp (flag)
SELECT flag FROM inserted

SELECT @maxpk = coalesce(MAX(pk), 0) FROM table1 WITH (UPDLOCK)

INSERT table1 (pk, flag)
SELECT @maxpk + ident, flag FROM @temp
go
INSERT table1 (flag)
SELECT OrderID FROM Northwind..Orders
go
SELECT * FROM table1
go
DROP TABLE table1
Of course, some people may ask why not use an IDENTITY column on
table1 directly? Well, assume that there is a business requirement
for a consecutive series of numbers, in which case IDENTITY won't do.

Then whether INSTEAD OF triggers is the way to go, I'm not really sure.
There is some extra maintenance job if you add more columns to the table.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #5

"Erland Sommarskog" <es****@sommarskog.se> wrote in message
news:Xn**********************@127.0.0.1...

Of course, some people may ask why not use an IDENTITY column on
table1 directly? Well, assume that there is a business requirement
for a consecutive series of numbers, in which case IDENTITY won't do.


I'm on a project right now where the requirement is to share surrogate
keys amongst three subtype tables that are all inherited from one supertype.
However, a much easier route was taken: Lock down the tables' write access
and only insert rows via a stored procedure. Personally, I find triggers
annoying to work with...
Jul 20 '05 #6
Adam Machanic (amachanic@hotmail._removetoemail_.com) writes:
I'm on a project right now where the requirement is to share surrogate
keys amongst three subtype tables that are all inherited from one
supertype. However, a much easier route was taken: Lock down the
tables' write access and only insert rows via a stored procedure.
Personally, I find triggers annoying to work with...


Yeah, for most of the tables where we have surrogate keys, we just
grab a MAX(id) in the insert stored procedure, and everything goes this
way. There are tables where we have IDENTITY, these mainly happens in the
table where the is an alternate natural key, but where need a surrogate
for some reason (for instance because the real key has one or more
nullable columns).

One problem with IDENTITY is that if you insert many rows at a time,
and you need to know the id value for each row, because you will also
insert rows in subtable.

Then we have these verification numbers that our system generates, but
which are not really surrogate keys - actually they are not always
even keys, and they are definite surrogates. They must be contiguous,
and also the different series must not collide. Here we have one one-
row, one-column table for each series.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #7

"Erland Sommarskog" <es****@sommarskog.se> wrote in message
news:Xn**********************@127.0.0.1...

Then we have these verification numbers that our system generates, but
which are not really surrogate keys - actually they are not always
even keys, and they are definite surrogates. They must be contiguous,
and also the different series must not collide. Here we have one one-
row, one-column table for each series.


What are you using those to verify? That sounds like it would be
difficult to maintain (MUST be contiguous)...
Jul 20 '05 #8
Mischa Sandberg (mi*************@telus.net) writes:
The exact English term is 'serial number' --- because they must be in
SERIES.
Actually, I looked it up in my dictionary which suggested "voucher number".
And while we tend to use "verifikation" to mean some sort of transaction,
the name comes from the fact that there is a piece of paper somewhere.
A receipt, a contract note or similar. In older days, the piecee of papers
where pre-printed with the number on them.
An IDENTITY column is not guaranteed to be exact contiguous series,
even though under certain circumstances it's darn close.
As long as no inserts fails...
To determine that all transactions are there, and haven't been tampered
with, would probably better rely on digital signatures and a digest
checksum.

Way too easy to resequence an identity:


Nah, that's an overkill. As I mentioned there is paper all over the place.
If the auditor sits with a note or someother printout which says number
123456, and transaction 123456 is something else, he will get very very
concerned.

--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #9

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

Similar topics

8
by: Stuart McGraw | last post by:
Is Microsoft full of #*$#*% (again) or am I badly misunderstanding something? Quote from Microsoft's T-SQL doc: > INSTEAD OF triggers are executed instead of the triggering action. > These...
4
by: Dan | last post by:
I am loading data from table A into table B. Certain columns in B have check constraints. I'd like for any rows from A, which violate constraints, to be inserted into a third table, C. When the...
0
by: Dave Sisk | last post by:
I've created a system or external trigger on an AS/400 file a.k.a DB2 table. (Note this is an external trigger defined with the ADDPFTRG CL command, not a SQL trigger defined with the CREATE...
2
by: Bruce | last post by:
I have an application written for version 8 that uses an INSTEAD OF trigger, and I need to convert it to support someone that needs it for v7. Is there a way to achieve similar functionality in...
2
by: Alex | last post by:
Hi, I need to create a trigger that will trap the insert commands on a table and if the row already exists, it updates the information. I started with this exemple but im getting syntax...
5
by: William of Ockham | last post by:
Hi, I was asked to recreate a new clean database for our developers because the current one they use is not entirely up to date. So I created a new database and I run into the followin strange...
5
by: Chris | last post by:
I'm attempting to get Instead Of triggers working. My platform in Solaris, DB2 verison 8.1.x (not sure which). If I create two simple tables with 1 row each: create table test_cc_1 (col1...
1
by: asf93555 | last post by:
Running under SQL2000 I can not get an INSTEAD trigger to function. I've even copied the example directl from books online - no joy . . . Server: Msg 170, Level 15, State 1, Procedure...
0
Brad Orders
by: Brad Orders | last post by:
Hi all Here is my situation: When table A is updated, I need to record some data in table B, then apply the update to table A Normally I would use a FOR UPDATE trigger, but the table has a...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...
0
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...

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.