You are here: Re: T-SQL create self-reference in depending table « MsSQL Server « IT news, forums, messages
Re: T-SQL create self-reference in depending table

Posted by Erland Sommarskog on 07/02/05 01:16

Wolfgang Kreuzer (wolfgang.m.kreuzer@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, esquel@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinfo/productdoc/2000/books.asp

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация