473,395 Members | 1,468 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.

T-SQL create self-reference in depending table

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
7 9653
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
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
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
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
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
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
Thanks that's a big help.

Sorry for late response, had problems with usenet account.

Wolfgang
Jul 23 '05 #8

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

Similar topics

6
by: dev | last post by:
how create a temp table as a copy of a existing table and then update1 field and insert the hole temp table back in the existing table? please any help? if i have 10 fields in 1 record and...
3
by: Michael Lauzon | last post by:
This is not for a class, I have a group on SourceForge, this is what one of the Developers is asking; the more advanced you can make it right off all the better!: Can someone please create...
2
by: Andreas | last post by:
Hi, can someone tell me how i do create a jump table in c or c++ ? I tried this: void f() { void *jump_table = { label1,
6
by: Jim's wife | last post by:
Hi all I need to create a new table based on a source table. The new table is almost the same as the source table in that just some field names must change, and a few new fields added or...
2
by: Maverick | last post by:
If i try to create foxpro table by the following "sql" statment, the C# compiler will only return an error "xxxx not support in non-dbc version". The "index on" command statement return some kind...
2
by: prakashwadhwani | last post by:
I have an app with a Front End and a Back-End. My date field is INV_DATE I would like to copy all data with year(inv_date) 2005 to a temp table in both, the front end & the back end. How...
3
by: Vee007 | last post by:
Following is my code: Dim objCatalog As ADOX.Catalog Dim objTableLink As ADOX.Table Dim objADOConnection As ADODB.Connection Try objADOConnection = New...
6
by: Michael D | last post by:
I want to create a different table for each sales person listed in a table. If I have salesperson1 through salespersonN listed in the table, I'd like to end up with a table for salesperson1 with just...
1
by: cardeal | last post by:
Hi! I have a long field on a mysql table and I would like to create a new table (from the old one) with the (new) content distributed into several fields. Example: oldField: 1. pace paz...
0
by: silwar | last post by:
Qusetion 1 I am developing a website mainly for maintaining students record in asp.net and using sql server 2005 database as backend. These site has three types of user Admin, faculty and...
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
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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
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...

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.