Showing posts with label inserts. Show all posts
Showing posts with label inserts. Show all posts

Monday, March 19, 2012

Nested inserts with TSQL

Hi I have to strings that can both each contain an indeterminable length. These strings are

UserID
NoteID

and will contain something like

UserID = '1, 2, 3, 4'
NoteID = '4, 9, 18, 21, 23, 27'

However its not known the length of each and so we could have the reverse of the above.

I am to insert x amount of notes to one userId and vice versa, but I'm trying to figure out how to do both so the insert would resemble the following.

UserID NoteID

1 4
1 9
1 18
1 21
1 23
1 27
2 4
2 9
etc, etc

This is sp that does it and it works fine for just one or the other, I just don't have much experience in this kind of thing. The spInsertAssignedNoteDetail at the end simply makes the insert when I have both numbers.

Heres my attempt, but i'm just stuck as to where to go from here

CREATE PROCEDURE spInsertAssignedNotesByList
@.FK_UserIDList NVARCHAR(4000) = NULL,
@.FK_NoteIDList NVARCHAR(4000) = NULL

AS
SET NOCOUNT ON

DECLARE @.Length INT
DECLARE @.Note_Length INT

DECLARE @.FirstUserIDWord NVARCHAR(4000)
DECLARE @.FK_UserID INT
DECLARE @.FK_NoteID INT

SELECT @.Length = DATALENGTH(@.FK_UserIDList )
SELECT @.Note_Length = DATALENGTH(@.FK_NoteIDList )

WHILE @.Length > 0 or @.Note_Length > 0
BEGIN
EXECUTE @.Length = PopFirstWord @.FK_UserIDList OUTPUT, @.FirstUserIDWord OUTPUT

IF @.Length > 0
BEGIN
SELECT @.FK_UserID = CONVERT(INT, @.FirstUserIDWord)

EXECUTE spInsertAssignedNoteDetail @.FK_UserID, @.FK_NoteID
END
END
----------------
GOOk I got this far, which does what I want with the first loop but when it comes to do the second outer do while for some reason the counter is zero instead of going backing to what it was when it started. Anyone know why it does this. Thanks

CREATE PROCEDURE spInsertAssignedNotesByList
@.FK_UserIDList NVARCHAR(4000) = NULL,
@.FK_NoteIDList NVARCHAR(4000) = NULL

AS
SET NOCOUNT ON

DECLARE @.Length INT
DECLARE @.Note_Length INT

DECLARE @.FirstUserIDWord NVARCHAR(4000)
DECLARE @.FirstNoteIDWord NVARCHAR(4000)

DECLARE @.FK_UserID INT
DECLARE @.FK_NoteID INT

SELECT @.Length = DATALENGTH(@.FK_UserIDList )
SELECT @.Note_Length = DATALENGTH(@.FK_NoteIDList )

WHILE @.Length > 0
BEGIN

IF @.Length > 0
EXECUTE @.Length = PopFirstWord @.FK_UserIDList OUTPUT, @.FirstUserIDWord OUTPUT
SELECT @.FK_UserID = CONVERT(INT, @.FirstUserIDWord)

WHILE @.Note_Length > 0
BEGIN
EXECUTE @.Note_Length = PopFirstWord @.FK_NoteIDList OUTPUT, @.FirstNoteIDWord OUTPUT
SELECT @.FK_NoteID = CONVERT(INT, @.FirstNoteIDWord)

IF @.Note_Length > 0
EXECUTE spInsertAssignedNoteDetail @.FK_UserID, @.FK_NoteID
END
END
----------------
GO

Saturday, February 25, 2012

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 OFFZRexRider (jerryg@.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, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||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|||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>|||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
--|||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|||ZRexRider (jerryg@.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, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||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
whether
>you 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. ;-)

Need to write value of session variable to SQL record

Each user who inserts a new SQL record from the FormView control needs to have their UserID in one of the fields of the record. I have the user ID stored in the Session("UserID") variable. I am having trouble finding the right way to get this done. I have tried using a hidden text box but I can't seem to assign the value. I have tried the Insert Parameters but that will not accept <%# Session("UserID") %> as a DefaultValue. Any ideas would be helpful. Thanks.

Try handling the ItemInserting event of your FormView where you can programmatically set the SqlDataSource.DefaultValue to your Session variable value. For example:

protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
{
SqlDataSource1.InsertParameters["UserID"].DefaultValue = Session["UserID"].ToString();
}|||Worked great with "(" instead of brackets "[". Thanks!|||I'm glad it worked out. My example was in C#. I guess you needed VB sample instead.|||You could of also created a SessionParameter and done it without any code at all.|||

Motley wrote:

You could of also created a SessionParameter and done it without any code at all.

Brilliant!!!