Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Mysql_insert_id equivalent for SQL Server

Status
Not open for further replies.

miraclemaker

Programmer
Oct 16, 2002
127
GB
Does anyone know if there's an equivalent of Mysql_insert_id for SQL server?

 
i dont think thats possible in SQL Server, i usually generate my own ids in SQLServer...

Known is handfull, Unknown is worldfull
 
I need to know how to do it through PHP so I can retrieve the last auto-incremented identity. Retrieving the last ID through Enterprise manager is not an option.

I've resorted to doing a query to find the row with the highest id that has the same values as the last row I inserted into the database.
 
Getting the max of the id is not a good idea. All it takes is for another record to have been inserted by another instantiation of your script and your app barfs.


If the folk in the SQL Server forum give you an answer that involved a SQL query, you could use it in PHP couldn't you?

Ask in the SQL Server forum. Sure, they may tell you that it can't be done through PHP. But then again they may know something about SQL Server that we don't.

Want the best answers? Ask the best questions: TANSTAAFL!!
 
You're correct, which is why I was hesitant to use this solution. It's not too bad though, as the other information that is added to the db includes the unique ID of the user, so fortunately the only way you could get the wrong id back would be if the same user was simultaniousely adding more rows, containing the same information.
 
Well I've asked, but I think the answer I'm going to get is to use MAX()
 
Are you after the identity of the last insert you did in which case you can select the identity column with the key you inserted with e.g.

insert into fred(keyfield,val) value ('john',28);
select identitycol from fred where keyfield = 'john';

But if you want to get the current identity for the table independent of anything else you can issue a dbcc call of checkident(fred) and capture the output e.g

create table reg (id int);
insert into reg exec ('dbcc checkindent(fred,NORESEED) with no_infomsgs');
select id from reg;

Which according to books online for sqlserver2000 will tell you the current identity column value. If I were you Id check my syntax as I don't have SQLserver on my PC

I'd be interested yo know how you get on.

Regards

Kevin
 
It was the first case scenario. I ended up doing something similar, but using MAX
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top