[posted and mailed, please reply in news]
Chris G (daddygiles@yahoo.com) writes:
[quoted text, click to view] > I'm using SQL Server 2000 and have an sp that inserts several rows
> into a table with an identity column. I want to use the identity
> values from my newly inserted records to create entries in a related
> table. How could I do this? @@IDENTITY only gives me the last row.
Maybe you should reconsider using the IDENTITY property at all. IDENTITY
sometimes comes in handy, but there are also situations where it causes
problems and this is one of them.
First thing to consider is whether you need an artificial primary key or
not. If there is a natural key in the data, use that key. This includes
the case, you combine data from two tables. If you have Products and
Warehouses, and a product can be in more than one warehouse, and you
have a ProductWarehouse table, the key of that table should be (ProductID,
WarehouseID), and not some meaningless IDENTITY key.
But not all data is well-formed enough to have a key that fulfils the
requirement of a primary key in a relational database. In this case, an
artificial key becomes necessary. But whether it should be an IDENTITY or
not, depends. For this particular situation, a good strategy is this:
CREATE TABLE #temp (ident int IDENTITY,
col1 ...
col2 ...)
INSERT #temp
SELECT ... -- Whereever you insert the data from today.
BEGIN TRANSCATION
-- Get next available id in target table. UPDLOCK is needed to prevent
-- some other process from getting the same key.
SELECT @id = coalesce(MAX(id), 0) + 1 FROM tbl (UPDLOCK)
INSERT target (id, col1, col2, ...)
SELECT @id + ident, col1, col2, ...
FROM #temp
-- Further processing follows.
...
COMMIT TRANSACTION
Here you use IDENTITY, but in a temp table to give you the numbers to
add to @id. This permits you easily retrieve the key value for each
inserted row.
--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
Books Online for SQL Server SP3 at