473,654 Members | 3,060 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.tblActiveSt ep_SortOrder

ON dbo.tblActiveSt ep

FOR INSERT
AS

-- Declare procedure level constants / variables / objects
----------------------------------------------------------------------------
DECLARE @intNextSortOrd erVal INT
SET NOCOUNT ON
-- Get the MAXimum sort value for steps in Pattern being added
-- and increment by 1
----------------------------------------------------------------------------
BEGIN
SELECT
@intNextSortOrd erVal= MAX(intSortOrde r) + 1 FROM tblActiveStep
WHERE
tblActiveStep.i ntActivePattern ID
IN
(SELECT inserted.intAct ivePatternID FROM inserted)

IF @intNextSortOrd erVal IS NULL
SELECT @intNextSortOrd erVal = 0
-- Set the intSortOrder Value with new calculated value
----------------------------------------------------------------------------
UPDATE
tblActiveStep SET intSortOrder = @intNextSortOrd erVal
WHERE
tblActiveStep.i ntActivePattern ID
IN
(SELECT inserted.intAct ivePatternID FROM inserted)
END
SET NOCOUNT OFF

Jul 23 '05 #1
7 2261
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
@intNextSortOrd erVal= MAX(intSortOrde r) + 1 FROM tblActiveStep
WHERE
tblActiveStep.i ntActivePattern ID
IN
(SELECT inserted.intAct ivePatternID 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 intActivePatter nID 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 intActivePatter nID, 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****@sommarsk og.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.tblActiveSt ep_SortOrder ON dbo.tblActiveSt ep
FOR INSERT AS

DECLARE @intNextSortOrd erVal INT

SET NOCOUNT ON

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

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

SELECT @intNextSortOrd erVal = coalesce(MAX(in tSortOrder), 0) + 1
FROM tblActiveStep a
WHERE EXISTS (SELECT *
FROM inserted i
WHERE a.intActivePatt ernID = i.intActivePatt ernID)

UPDATE tblActiveStep
SET intSortOrde = @intNextSortOrd erVal
FROM tblActiveStep a
WHERE EXISTS (SELECT *
FROM inserted i
WHERE a.intActivePatt ernID = i.intActivePatt ernID)
AND nullif(intSortO rder, 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****@sommarsk og.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
4761
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, PARENT_CATEGORY_ID INTEGER, CATEGORY_ICON IMAGE, DEPTH INTEGER,
7
2046
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 command on it's table and the where condition returns only one row, the trigger is executed ok, but if where condition returns more than one rows, the trigger don't run. I don't know what happens there...
2
2515
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 been inserted. The sequence number can only be created after we go to the second line. Please see the trigger below. Is there anyway we could create a trigger that could create the sequence number as soon as we enter a value? It should be...
2
1114
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 language. I've read some Java and i have tried to learn java but really haven't gotten the time yet so i know a bit OO. ( i tend to fall back to languages i know i guess ;) but i see that .Net is worth learning for me )
0
1831
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 different ways and none of the versions i've made works exactly as it should. I have an array called $PageArray which contains a sorted list of all pages in my application. Im trying to create a recursive function(It dosn't need to be recursive if...
2
4966
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 still not working correctly. Here is my code: create trigger emp_update_id BEFORE update on emp_update REFERENCING NEW AS N for each row SET unique_id = Generate_unique();
1
1451
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 trigger say "trigger A"so the current process executed in the queue is paused. Then i issue another trigger "trigger B". Scenario 1: Considering the two triggers are not related. Upon issuing trigger B should trigger A be paused? Or Is it...
7
3297
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 following trigger create trigger chk_team on teams for insert as declare @chkCountry as char(2)
3
1644
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 creating the following TRIGGER:
0
8379
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
8294
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
8709
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8494
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
8596
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7309
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
6162
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
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4297
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.