473,395 Members | 1,678 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,395 software developers and data experts.

Need Trigger Help

Hi,

I have trigger that enforces the creation of a sortorder that is always
1 digit higher than the current highest on Inserts.

This trigger works great if I add one row at a time so I think the
logic is sound. However, I have a Stored Procedure that copies a bunch
of rows into this table and all of the SortOrder values come up as 0.
This stored procedure is doing an "Insert Into" and will insert
numerous rows (10-20) at once.

Since these rows are being inserted is it possible that this trigger
doesn't see the new rows? Is it a timing thing?

Thanks - trigger is below

-------------------------------------------------
ALTER TRIGGER dbo.tblActiveStep_SortOrder

ON dbo.tblActiveStep

FOR INSERT
AS

-- Declare procedure level constants / variables / objects
----------------------------------------------------------------------------
DECLARE @intNextSortOrderVal INT
SET NOCOUNT ON
-- Get the MAXimum sort value for steps in Pattern being added
-- and increment by 1
----------------------------------------------------------------------------
BEGIN
SELECT
@intNextSortOrderVal= MAX(intSortOrder) + 1 FROM tblActiveStep
WHERE
tblActiveStep.intActivePatternID
IN
(SELECT inserted.intActivePatternID FROM inserted)

IF @intNextSortOrderVal IS NULL
SELECT @intNextSortOrderVal = 0
-- Set the intSortOrder Value with new calculated value
----------------------------------------------------------------------------
UPDATE
tblActiveStep SET intSortOrder = @intNextSortOrderVal
WHERE
tblActiveStep.intActivePatternID
IN
(SELECT inserted.intActivePatternID FROM inserted)
END
SET NOCOUNT OFF

Jul 23 '05 #1
7 2251
ZRexRider (je****@ptd.net) writes:
I have trigger that enforces the creation of a sortorder that is always
1 digit higher than the current highest on Inserts.

This trigger works great if I add one row at a time so I think the
logic is sound. However, I have a Stored Procedure that copies a bunch
of rows into this table and all of the SortOrder values come up as 0.
This stored procedure is doing an "Insert Into" and will insert
numerous rows (10-20) at once.

Since these rows are being inserted is it possible that this trigger
doesn't see the new rows? Is it a timing thing?
No.

It's not clear to me what the trigger is supposed to achieve. What it
would achieve is to set the same sort order for all rows inserted in
the one and same INSERT statement. Recall that a trigger fires once
per statement, not once per row.
SELECT
@intNextSortOrderVal= MAX(intSortOrder) + 1 FROM tblActiveStep
WHERE
tblActiveStep.intActivePatternID
IN
(SELECT inserted.intActivePatternID FROM inserted)


Apparently this yields NULL in some situations. Since I don't know
the tables, it's a little difficult to say what is happening. Does
intSortOrder have a value on input? Is intActivePatternID a key,
or could there already be rows with that value. If goes without saying
that if intSortOrder is NULL on INSERT, and you insert a copied new
rows with intActivePatternID, this SELECT will yeild NULL.

It's always for this kind of problem to post:

o CREATE TABLE statement for the involved table(s). Don't forget the keys.
o INSERT statement with sample data.
o The desired result given the sample data.

--
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 23 '05 #2
Thanks - your tip (Trigger fires once per statement not row) tells me
why it doesn't work.

My goal was to add a bunch of rows to a table but I wanted them to
automatically set their sort order to be the next sequential number in
its family.

I.E

Existing demo table

ID Desc SortOrder
1 ABC 0
2 DEF 1
3 CBA 2

Now my query runs and wants to add the following 3 rows

Desc
XXX
YYY
ZZZZ

ID Desc SortOrder
1 ABC 0
2 DEF 1
3 CBA 2
4 XXX 3
5 YYY 4
6 ZZZ 5

Of course... the trigger was working form me every time a record was
manually entered and I don't want to remove the trigger. So, if it
won't work on a bulk insert I'll need to temporarily disable the
trigger during the bulk insert

Thanks for the response

Jul 23 '05 #3
Just in case somebody else Googles this thread, my solution is to
disable the trigger during this multiple insert and re-enable it once
done.

I failed to mention - the data being copied has its own SortOrder
values. I was not including them in the INSERT because I had this
trigger in place to automatically add the sort order and increment it.
I want this trigger because the sort order is important and it nicely
handles the manual rows added in the normal use of the application.
When a user adds a record - it gets sorted to the end. They can use my
interface to move rows up and down but my Adds always go to the end.
Works nicely.

So since I'm copying a set of master records into another table, I
simply disable the SortOrder trigger - insert the rows and enable the
SortOrder trigger.

In my case there is very little risk because the number of users are
small and the person running this "copy" function is pretty much the
same person who will be adding individual rows later. However, there
is always the chance that during this second that the trigger is off -
somebody could sneak in a manualy entered record someplace else. I'm
more likely to get hit by lightning.

Syntax:

ALTER TABLE <table name>
<ENABLE|DISABLE> TRIGGER <ALL|<trigger name>>

Jul 23 '05 #4
Your "solution" is dangerous and anyway is redundant - why not just
write a trigger that performs correctly with multiple rows instead?

As Erland explained, if you gave us a proper spec I'm sure we could
help you better. In what order would you want to define the sort if
multiple rows were inserted? If you don't care about the order then why
not just default to NULL or 0.

--
David Portas
SQL Server MVP
--

Jul 23 '05 #5
Thanks David

I appreciate your input. Again danger is relative and there is no
redundancy in my solution. It simply copies contents of a
master/template table to and active table.

My requirements are simple:

This portion of my application has a Master/Detail relationship

I have a trigger placed on a field called intSortOrder in the Detail
table so that every individual INSERT into the detail table gets
assigned the next sequential Sort Order. So let's say there are 32
Detail rows associated with Master ID 8. When the user enters a new
item to be associated with item 8, it's sort order will be set to 33.
They will use this method frequently.

The problem arises because I have a special function that lets you
copy/clone a Master and all of it's related detail rows into a similar
pair of tables for special use. The detail table for the receiving
table also wants to enforce the values in the sort order. However,
when I ran the stored procedure it simply gave the intSortOrder value
the same value for each ane every record.

Erland pointed out to me that triggers are do not re-fire for every row
- fire for the Insert statement.

The sort order is important so NULL or 0 is not acceptable.

So although I want the trigger for those frequent manual "adds" done by
my user - it isn't going to help me on the bulk insert.

As per your question: why not just write a trigger that performs
correctly with multiple rows instead?

I have limited experience with triggers - as I learn more I will
certainly do so.

Thanks for the nudge

Jul 23 '05 #6
ZRexRider (je****@ptd.net) writes:
So although I want the trigger for those frequent manual "adds" done by
my user - it isn't going to help me on the bulk insert.
By default triggers don't fire when you insert data with the BULK INSERT
statement. But it appears that you with "bulk insert" means a plain INSERT
statement that inserts more than row.
As per your question: why not just write a trigger that performs
correctly with multiple rows instead?

I have limited experience with triggers - as I learn more I will
certainly do so.


That's a poor excuse for a bad design. Of course, I have no idea whether
you are doing this as a hobby, or someone is paying you for this.

It still very unclear to me what you are really trying to achieve,
but assuming that the mass-inserted rows already have a sortorder > 1,
this is possible trigger:

CREATE TRIGGER dbo.tblActiveStep_SortOrder ON dbo.tblActiveStep
FOR INSERT AS

DECLARE @intNextSortOrderVal INT

SET NOCOUNT ON

IF NOT EXISTS (SELECT *
FROM inserted
WHERE nullif(intSortOrder, 0) IS NULL)
RETURN

IF (SELECT COUNT(*) FROM inserted) > 1
BEGIN
ROLLBACK TRANSACTION
RAISERROR('Multi-row inserts with NULL sortorder not permitted!', 16, 1)
RETURN
END

SELECT @intNextSortOrderVal = coalesce(MAX(intSortOrder), 0) + 1
FROM tblActiveStep a
WHERE EXISTS (SELECT *
FROM inserted i
WHERE a.intActivePatternID = i.intActivePatternID)

UPDATE tblActiveStep
SET intSortOrde = @intNextSortOrderVal
FROM tblActiveStep a
WHERE EXISTS (SELECT *
FROM inserted i
WHERE a.intActivePatternID = i.intActivePatternID)
AND nullif(intSortOrder, 0) IS NULL

Still not perfect, but since I don't know the keys of your data, it's
difficult to make it better.

--
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 23 '05 #7
Thanks again for your help and for the time you spent on the code
example. I think you set me straight in your first response where you
pointed out that a trigger does not fire per row but per statement. If
that information is correct, and I believe it is, then there is no
point trying to insert multiple rows and have them receive incrimented
sortorder values via a trigger. As with my original trigger - your
trigger produces the same results - all rows get the value of 1 for
their sort order.

That's a poor excuse for a bad design. Of course, I have no idea whetheryou are doing this as a hobby, or someone is paying you for this.
Thanks for your opinion.
It still very unclear to me what you are really trying to achieve,


I guess it's just too simple to explain. ;-)

Jul 23 '05 #8

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

Similar topics

33
by: coosa | last post by:
I have a table: ---------------------------------------------------- CREATE TABLE CATEGORY ( CATEGORY_ID INTEGER IDENTITY(1,1) NOT NULL, CATEGORY_NAME VARCHAR(40) NOT NULL,...
7
by: Lucio Chiessi | last post by:
Hi for all on this... I'm using MS SQL Server 7.0 SP4 in some customers to store some data from an aplication developed by me. I created an trigger to run on update. When I run an update...
2
by: Ken | last post by:
I got an Access database that need to be converted to Oracle 9i. Somehow the Trigger we created to simulate the "AUTO NUMBER" on Access could not create the sequence number as soon as the value has...
2
by: Kai Thorsrud | last post by:
Hi, I'm a selv learned developer and I have a few years of experience with VB6, ASP, PHP and such. I've dug into coding with VB.NET and this language simply amazes me. I really LOVE this...
0
by: Michael L | last post by:
Hi Guys(I apologize for the lengty post - Im trying to explain it as best i can) I've been cracking my head on this one for the past 24+ hours and i have tried creating the function in ten...
2
by: mob1012 via DBMonster.com | last post by:
Hi All, I wrote last week about a trigger problem I was having. I want a trigger to produce a unique id to be used as a primary key for my table. I used the advice I received, but the trigger is...
1
by: nDaKota | last post by:
I am current converting PowerBuilder to C#. Now I'm having problem on triggers. I understand what a triggers does. The problem is what happens if a trigger is being triggered? Example: I execute a...
7
by: Shane | last post by:
I have been instructed to write a trigger that effectively acts as a foreign key. The point (I think) is to get me used to writing triggers that dont use the primary key(s) I have created the...
3
by: lenygold via DBMonster.com | last post by:
Hi everybody! I have an INSERT stattement like this: insert into ELIGIBLE_PAY select from ELIGIBLE_PAY_B where cust_id = 999999; after insert i would like to delete row from source table by...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...
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
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...
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...

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.