By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,679 Members | 2,185 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,679 IT Pros & Developers. It's quick & easy.

T-SQL create self-reference in depending table

P: n/a
Hello all,

I have two tables - Projects and ProjectStruct
Table Projects contains master records of the projects, ProjectStruct
allows to define a project herarchie and contains the fields
PrjStructId, ProjectId, PrjStructName, ..., ParentId

PrjStructParent contains a reference to the parent or to itselves if
record is top-level-record for a project.

I try to create a trigger on table Projects (INSERT) which
automatically creates the top-level-entry in ProjectStruct but I
didn't succed.

Tried to use (several variations similar to)

INSERT INTO ProjectStruct (ProjectId, PrjStructName, ParentId)
SELECT prjProjectId, 'top-level',IDENT_CURRENT('ProjectStruct'))
FROM INSERTED

but this inserts a reference to the last inserted record. Why this
happens is pretty clear to me, but I found no way to get the reference
to the identity column of the record currently inserted.

Is there a way to do this?
Jul 23 '05 #1
Share this Question
Share on Google+
7 Replies


P: n/a
Wolfgang Kreuzer (wo****************@gmx.de) writes:
I try to create a trigger on table Projects (INSERT) which
automatically creates the top-level-entry in ProjectStruct but I
didn't succed.

Tried to use (several variations similar to)

INSERT INTO ProjectStruct (ProjectId, PrjStructName, ParentId)
SELECT prjProjectId, 'top-level',IDENT_CURRENT('ProjectStruct'))
FROM INSERTED
Note that IDENT_CURRENT returns a value that is server-global, and
thus may be affected by the activity of other process. You proabably
do not want this one where.
but this inserts a reference to the last inserted record. Why this
happens is pretty clear to me, but I found no way to get the reference
to the identity column of the record currently inserted.

Is there a way to do this?


Nope, not in the dead end you are now.

The best is probably to remove the IDENTITY property from the table
and roll your own. That's pretty easy:

DECLARE @newids (ident int IDENTITY,
prjProjectID int NOT NULL)
DECLARE @nextid int
SELECT @nextid = coalesce(MAX(ProjectStructID), 0) + 1
FROM ProjectStruct WITH (UPDLOCK)

INSERT (prjProjectID) SELECT prjProjectID FROM inserted

INSERT ProjectStruct (ProjectId, PrjStructName, ParentId)
SELECT projProjectID, 'top level', @nextid + ident - 1
FROM @newids

The table variable is needed to cater for multi-row inserts.

A more common approach, though, is to leave the parent NULL for
the top-level object.

--
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

P: n/a
Erland,
thanks for your interesting answer. It provides a lot to learn for me,
comming from Access and still getting clobbered over the head with the
options provided by TSQL.

Meanwhile I found an easier way to solve my original problem:
- adding rows in the first step to ProjectStruct, leaving ParentId
NULL
- updating ProjectStruct in inserted rows having ParentId=NULL in 2nd
step, which is quite easy to do as the rows can be identified by
INSERTED

Have no idea why I didn't find that immediately - maybe I was to
focussed on a solution to do it in one step.

Wolfgang

On Fri, 1 Jul 2005 22:16:51 +0000 (UTC), Erland Sommarskog
<es****@sommarskog.se> wrote:
Wolfgang Kreuzer (wo****************@gmx.de) writes:
I try to create a trigger on table Projects (INSERT) which
automatically creates the top-level-entry in ProjectStruct but I
didn't succed.

Tried to use (several variations similar to)

INSERT INTO ProjectStruct (ProjectId, PrjStructName, ParentId)
SELECT prjProjectId, 'top-level',IDENT_CURRENT('ProjectStruct'))
FROM INSERTED


Note that IDENT_CURRENT returns a value that is server-global, and
thus may be affected by the activity of other process. You proabably
do not want this one where.
but this inserts a reference to the last inserted record. Why this
happens is pretty clear to me, but I found no way to get the reference
to the identity column of the record currently inserted.

Is there a way to do this?


Nope, not in the dead end you are now.

The best is probably to remove the IDENTITY property from the table
and roll your own. That's pretty easy:

DECLARE @newids (ident int IDENTITY,
prjProjectID int NOT NULL)
DECLARE @nextid int
SELECT @nextid = coalesce(MAX(ProjectStructID), 0) + 1
FROM ProjectStruct WITH (UPDLOCK)

INSERT (prjProjectID) SELECT prjProjectID FROM inserted

INSERT ProjectStruct (ProjectId, PrjStructName, ParentId)
SELECT projProjectID, 'top level', @nextid + ident - 1
FROM @newids

The table variable is needed to cater for multi-row inserts.

A more common approach, though, is to leave the parent NULL for
the top-level object.


Jul 23 '05 #3

P: n/a
Get a copy of TREES & HIERARCHIES IN SQL. You can use the nested sets
model and completely avoid all of this procedural code.

Then take the time to learn RDBMS, so you will know that a row is not a
record and a column is not field and that there is no "last inserted
record" because SQL works with entire sets and has no ordering -- those
are terms from a sequential file system. No wonder you think in terms
of triggers and procedural code.

It is soooo much easier to program SQL when you have the right mental
models.

Jul 23 '05 #4

P: n/a
Hello Joe,
thanks for your comments.

Where can I find 'TREES & HIERARCHIES IN SQL'? Do you have an ISBN or
a unique refeference to look for it?

My programming history is C, VB and Axs 2.0 - I worte an application
which I migrate to SQL-Server and Axs 2k by using the look and feel of
my app but starting from the scratch as I want to use the benefits of
a real RDBMS.

My wording may be wrong, but wording is one point. My approach solving
the problem of inserting entries, rows or recods or blubbs in a table
was to to use a single SQL statement, but I was unable to find a way
to get a reference to an identity field in the same record, but I
didn't succeed. If there is a way to do so; I would love to kwon how.

My current (set-based) way is:

INSERT INTO dbo.prjProjectStruct (prsProjectId, prsPSPName,
prsPSPIdent, prsUserIdPrjMan, prsIsActive, prsParentId, CreaDate,
CreaSessInstId, LastModiDate, LastModiSessInstId)
SELECT INSERTED.prjProjectId, 'Gesamtprojekt', null,
dbo.prjSysUser2User.su2uUserId, 1, NULL,
@dtNow, @iSessInstId, @dtNow, @iSessInstId
FROM INSERTED INNER JOIN dbo.prjSysUser2User ON
INSERTED.prjSysUserIdOwner =
dbo.prjSysUser2User.su2uSysUserId WHERE
(dbo.prjSysUser2User.su2uIsMainEntry = 1)

--################################################## #########
--### update parent id in inserted rows in prjProjectStruct
--################################################## #########
UPDATE dbo.prjProjectStruct
SET prsParentId=prsPrjStructId
FROM dbo.prjProjectStruct INNER JOIN INSERTED ON
dbo.prjProjectStruct.prsProjectId = INSERTED.prjProjectId
WHERE prsParentId IS NULL

I am now fully happy with this solution, but IMHO it isn't to bad. If
there is a way to to do it easier, I am always open to learn from
others.

Bye
On 2 Jul 2005 09:24:21 -0700, "--CELKO--" <jc*******@earthlink.net>
wrote:
Get a copy of TREES & HIERARCHIES IN SQL. You can use the nested sets
model and completely avoid all of this procedural code.

Then take the time to learn RDBMS, so you will know that a row is not a
record and a column is not field and that there is no "last inserted
record" because SQL works with entire sets and has no ordering -- those
are terms from a sequential file system. No wonder you think in terms
of triggers and procedural code.

It is soooo much easier to program SQL when you have the right mental
models.


Jul 23 '05 #5

P: n/a
TREES & HIERARCHIES IN SQL (Morgan-Kaufmann), 2004 ISBN 1-55860-920-2

Regards
--------------------------------
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland

IM: mi**@epprecht.net

MVP Program: http://www.microsoft.com/mvp

Blog: http://www.msmvps.com/epprecht/

"Wolfgang Kreuzer" <wo****************@gmx.de> wrote in message
news:1120335173.ac80700d2cdb088b93b1c46d0ec5f847@t eranews...
Hello Joe,
thanks for your comments.

Where can I find 'TREES & HIERARCHIES IN SQL'? Do you have an ISBN or
a unique refeference to look for it?

My programming history is C, VB and Axs 2.0 - I worte an application
which I migrate to SQL-Server and Axs 2k by using the look and feel of
my app but starting from the scratch as I want to use the benefits of
a real RDBMS.

My wording may be wrong, but wording is one point. My approach solving
the problem of inserting entries, rows or recods or blubbs in a table
was to to use a single SQL statement, but I was unable to find a way
to get a reference to an identity field in the same record, but I
didn't succeed. If there is a way to do so; I would love to kwon how.

My current (set-based) way is:

INSERT INTO dbo.prjProjectStruct (prsProjectId, prsPSPName,
prsPSPIdent, prsUserIdPrjMan, prsIsActive, prsParentId, CreaDate,
CreaSessInstId, LastModiDate, LastModiSessInstId)
SELECT INSERTED.prjProjectId, 'Gesamtprojekt', null,
dbo.prjSysUser2User.su2uUserId, 1, NULL,
@dtNow, @iSessInstId, @dtNow, @iSessInstId
FROM INSERTED INNER JOIN dbo.prjSysUser2User ON
INSERTED.prjSysUserIdOwner =
dbo.prjSysUser2User.su2uSysUserId WHERE
(dbo.prjSysUser2User.su2uIsMainEntry = 1)

--################################################## #########
--### update parent id in inserted rows in prjProjectStruct
--################################################## #########
UPDATE dbo.prjProjectStruct
SET prsParentId=prsPrjStructId
FROM dbo.prjProjectStruct INNER JOIN INSERTED ON
dbo.prjProjectStruct.prsProjectId = INSERTED.prjProjectId
WHERE prsParentId IS NULL

I am now fully happy with this solution, but IMHO it isn't to bad. If
there is a way to to do it easier, I am always open to learn from
others.

Bye
On 2 Jul 2005 09:24:21 -0700, "--CELKO--" <jc*******@earthlink.net>
wrote:
Get a copy of TREES & HIERARCHIES IN SQL. You can use the nested sets
model and completely avoid all of this procedural code.

Then take the time to learn RDBMS, so you will know that a row is not a
record and a column is not field and that there is no "last inserted
record" because SQL works with entire sets and has no ordering -- those
are terms from a sequential file system. No wonder you think in terms
of triggers and procedural code.

It is soooo much easier to program SQL when you have the right mental
models.

Jul 23 '05 #6

P: n/a
It is on Amazon.com. here is the whole list:

Joe Celko's Data and Databases : Concepts in Practice 1-55860-432-4
Joe Celko's SQL Programming Style 0-12-088797-5
Joe Celko's SQL Puzzles and Answers 5 1-55860-453-7
Joe Celko's Trees and Hierarchies in SQL for Smarties $34.95
1-55860-920-2
Joe Celko's SQL for Smarties:Advanced SQL Programming Second Edition
1-55860-576-2
Joe Celko's SQL for Smarties (3rd Edition): Advanced SQL Programming
Joe Celko 0-12-369379-9
but I was unable to find a way to get a reference to an identity field [sic] in the same record[sic] <<


Again, if you keep using the wrong terms, you will never see how write
code in a declarative relational language.

Nexr, you should never use IDENTIT. It is not relational and **by
definition** cannot be a key.

There are many ways to represent a tree or hierarchy in SQL. This is
called an adjacency list model and it looks like this:

CREATE TABLE OrgChart
(emp CHAR(10) NOT NULL PRIMARY KEY,
boss CHAR(10) DEFAULT NULL REFERENCES OrgChart(emp),
salary DECIMAL(6,2) NOT NULL DEFAULT 100.00);

OrgChart
emp boss salary
===========================
'Albert' NULL 1000.00
'Bert' 'Albert' 900.00
'Chuck' 'Albert' 900.00
'Donna' 'Chuck' 800.00
'Eddie' 'Chuck' 700.00
'Fred' 'Chuck' 600.00

Another way of representing trees is to show them as nested sets.

Since SQL is a set oriented language, this is a better model than the
usual adjacency list approach you see in most text books. Let us define
a simple OrgChart table like this.

CREATE TABLE OrgChart
(emp CHAR(10) NOT NULL PRIMARY KEY,
lft INTEGER NOT NULL UNIQUE CHECK (lft > 0),
rgt INTEGER NOT NULL UNIQUE CHECK (rgt > 1),
CONSTRAINT order_okay CHECK (lft < rgt) );

OrgChart
emp lft rgt
======================
'Albert' 1 12
'Bert' 2 3
'Chuck' 4 11
'Donna' 5 6
'Eddie' 7 8
'Fred' 9 10

The organizational chart would look like this as a directed graph:

Albert (1, 12)
/ \
/ \
Bert (2, 3) Chuck (4, 11)
/ | \
/ | \
/ | \
/ | \
Donna (5, 6) Eddie (7, 8) Fred (9, 10)

The adjacency list table is denormalized in several ways. We are
modeling both the Personnel and the organizational chart in one table.
But for the sake of saving space, pretend that the names are job titles
and that we have another table which describes the Personnel that hold
those positions.

Another problem with the adjacency list model is that the boss and
employee columns are the same kind of thing (i.e. names of personnel),
and therefore should be shown in only one column in a normalized table.
To prove that this is not normalized, assume that "Chuck" changes his
name to "Charles"; you have to change his name in both columns and
several places. The defining characteristic of a normalized table is
that you have one fact, one place, one time.

The final problem is that the adjacency list model does not model
subordination. Authority flows downhill in a hierarchy, but If I fire
Chuck, I disconnect all of his subordinates from Albert. There are
situations (i.e. water pipes) where this is true, but that is not the
expected situation in this case.

To show a tree as nested sets, replace the nodes with ovals, and then
nest subordinate ovals inside each other. The root will be the largest
oval and will contain every other node. The leaf nodes will be the
innermost ovals with nothing else inside them and the nesting will show
the hierarchical relationship. The (lft, rgt) columns (I cannot use the
reserved words LEFT and RIGHT in SQL) are what show the nesting. This
is like XML, HTML or parentheses.

At this point, the boss column is both redundant and denormalized, so
it can be dropped. Also, note that the tree structure can be kept in
one table and all the information about a node can be put in a second
table and they can be joined on employee number for queries.

To convert the graph into a nested sets model think of a little worm
crawling along the tree. The worm starts at the top, the root, makes a
complete trip around the tree. When he comes to a node, he puts a
number in the cell on the side that he is visiting and increments his
counter. Each node will get two numbers, one of the right side and one
for the left. Computer Science majors will recognize this as a modified
preorder tree traversal algorithm. Finally, drop the unneeded
OrgChart.boss column which used to represent the edges of a graph.

This has some predictable results that we can use for building queries.
The root is always (left = 1, right = 2 * (SELECT COUNT(*) FROM
TreeTable)); leaf nodes always have (left + 1 = right); subtrees are
defined by the BETWEEN predicate; etc. Here are two common queries
which can be used to build others:

1. An employee and all their Supervisors, no matter how deep the tree.

SELECT O2.*
FROM OrgChart AS O1, OrgChart AS O2
WHERE O1.lft BETWEEN O2.lft AND O2.rgt
AND O1.emp = :myemployee;

2. The employee and all their subordinates. There is a nice symmetry
here.

SELECT O1.*
FROM OrgChart AS O1, OrgChart AS O2
WHERE O1.lft BETWEEN O2.lft AND O2.rgt
AND O2.emp = :myemployee;

3. Add a GROUP BY and aggregate functions to these basic queries and
you have hierarchical reports. For example, the total salaries which
each employee controls:

SELECT O2.emp, SUM(S1.salary)
FROM OrgChart AS O1, OrgChart AS O2,
Salaries AS S1
WHERE O1.lft BETWEEN O2.lft AND O2.rgt
AND O1.emp = S1.emp
GROUP BY O2.emp;

4. To find the level of each emp, so you can print the tree as an
indented listing. Technically, you should declare a cursor to go with
the ORDER BY clause.

SELECT COUNT(O2.emp) AS indentation, O1.emp
FROM OrgChart AS O1, OrgChart AS O2
WHERE O1.lft BETWEEN O2.lft AND O2.rgt
GROUP BY O1.lft, O1.emp
ORDER BY O1.lft;

5. The nested set model has an implied ordering of siblings which the
adjacency list model does not. To insert a new node, G1, under part G.
We can insert one node at a time like this:

BEGIN ATOMIC
DECLARE rightmost_spread INTEGER;

SET rightmost_spread
= (SELECT rgt
FROM Frammis
WHERE part = 'G');
UPDATE Frammis
SET lft = CASE WHEN lft > rightmost_spread
THEN lft + 2
ELSE lft END,
rgt = CASE WHEN rgt >= rightmost_spread
THEN rgt + 2
ELSE rgt END
WHERE rgt >= rightmost_spread;

INSERT INTO Frammis (part, lft, rgt)
VALUES ('G1', rightmost_spread, (rightmost_spread + 1));
COMMIT WORK;
END;

The idea is to spread the (lft, rgt) numbers after the youngest child
of the parent, G in this case, over by two to make room for the new
addition, G1. This procedure will add the new node to the rightmost
child position, which helps to preserve the idea of an age order among
the siblings.

6. To convert a nested sets model into an adjacency list model:

SELECT B.emp AS boss, E.emp
FROM OrgChart AS E
LEFT OUTER JOIN
OrgChart AS B
ON B.lft
= (SELECT MAX(lft)
FROM OrgChart AS S
WHERE E.lft > S.lft
AND E.lft < S.rgt);

7. To convert an adjacency list to a nested set model, use a push down
stack. Here is version with a stack in SQL/PSM.

-- Tree holds the adjacency model
CREATE TABLE Tree
(node CHAR(10) NOT NULL,
parent CHAR(10));

-- Stack starts empty, will holds the nested set model
CREATE TABLE Stack
(stack_top INTEGER NOT NULL,
node CHAR(10) NOT NULL,
lft INTEGER,
rgt INTEGER);

CREATE PROCEDURE TreeTraversal ()
LANGUAGE SQL
DETERMINISTIC
BEGIN ATOMIC
DECLARE counter INTEGER;
DECLARE max_counter INTEGER;
DECLARE current_top INTEGER;

SET counter = 2;
SET max_counter = 2 * (SELECT COUNT(*) FROM Tree);
SET current_top = 1;

--clear the stack
DELETE FROM Stack;

-- push the root
INSERT INTO Stack
SELECT 1, node, 1, max_counter
FROM Tree
WHERE parent IS NULL;

-- delete rows from tree as they are used
DELETE FROM Tree WHERE parent IS NULL;

WHILE counter <= max_counter- 1
DO IF EXISTS (SELECT *
FROM Stack AS S1, Tree AS T1
WHERE S1.node = T1.parent
AND S1.stack_top = current_top)
THEN BEGIN -- push when top has subordinates and set lft value
INSERT INTO Stack
SELECT (current_top + 1), MIN(T1.node), counter, NULL
FROM Stack AS S1, Tree AS T1
WHERE S1.node = T1.parent
AND S1.stack_top = current_top;

-- delete rows from tree as they are used
DELETE FROM Tree
WHERE node = (SELECT node
FROM Stack
WHERE stack_top = current_top + 1);
-- housekeeping of stack pointers and counter
SET counter = counter + 1;
SET current_top = current_top + 1;
END;
ELSE
BEGIN -- pop the stack and set rgt value
UPDATE Stack
SET rgt = counter,
stack_top = -stack_top -- pops the stack
WHERE stack_top = current_top;
SET counter = counter + 1;
SET current_top = current_top - 1;
END;
END IF;
END WHILE;
-- SELECT node, lft, rgt FROM Stack;
-- the top column is not needed in the final answer
-- move stack contents to new tree table
END;

Jul 23 '05 #7

P: n/a
Thanks that's a big help.

Sorry for late response, had problems with usenet account.

Wolfgang
Jul 23 '05 #8

This discussion thread is closed

Replies have been disabled for this discussion.