PDA

View Full Version : Setting a table field based on another table's last entry


zenweezil
09-12-2005, 10:45 PM
Is there anyway to set up a SQL database table column to number itself based on the last entry in a different table?

Example:

"Table a" has a field tablebID that needs to be the next number available from "Table b" ID field.

So if "Table b" looked like this:
ID, ENTRY
1, first entry
2, second entry
3, third entry

The next entry in "Table a" would automatically assign 4 to the tablebID column.

Anyone follow that? Is that possible to do in the SQL Server database structure?

Roelf
09-13-2005, 10:44 AM
But what should happen if the last record in table b is deleted, the next autonumber (if you have the id in table b as an autonumber with increment 1) would still be 4, because id's are not automatically re-used.
Is the desired entry in table a still 4 or is it 3?

Tell us what you are trying to do, there might be a better solution to find

zenweezil
09-13-2005, 03:23 PM
It wouldn't matter if it was 3 or 4 as long as it remained unique and corresponded between tables.

The reason I want the database structure to handle this rather than having an asp page call out the last ID of table B and insert into table a is because all the rest of the entry is being submitted via a csv import and I can't add those to the csv and am not sure how to insert other fields simulatenously wiht the csv import.

One thought is to find a more manual way to import the csv as of now I was using an Interakt extension - perhaps if I could find some code on how to hardcode a csv INSERT I could include my ID fields.

Roelf
09-14-2005, 08:21 AM
well, you could use a trigger which fires after the insert. Let the trigger find out the id of the inserted record. Then store that id in table a

CREATE TRIGGER StoreNewId ON [dbo].[b]
FOR INSERT
AS
UPDATE a SET TableBid = ((SELECT id FROM inserted) + 1)

it needs one record in table a, but this should work

zenweezil
09-15-2005, 11:26 PM
Thanks, I'll give that a try.