Wednesday, March 7, 2012

Returning the next identity value before writing a record.

I am storing product information in a SQL Server database table; the product information has no unique fields so I have created an Identity field called 'uid'. Is there a way of querying the table to find out what value will be given to the next 'uid' field before the next record is written to the table? I need to use this as a FK in other tables.There is not any safe way of doing that. You can query the table for the current highest number, but that will fail when multiple users are hitting the database.
Insert the new row and the related rows in a transaction, or add a "Pending" flag to the table, and have it default to True (meaning it is pending) and then have other parts of the system look for Pending==false rows.|||you can change the data type to uniqueidentifier, that way you'll knowthe id of that row since you'll be passing it a Guid that you create.
|||

In SQL Server GUID is a 16bytes binary data type, run a search for NEWID in the BOL (books online) and another option is DBCC CHECKIDENTITY. Try the link below for DBCC CHECKIDENTITY. Hope this helps.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_dbcc_5lv8.asp

No comments:

Post a Comment