I just want to get a unique int value to assign it to every record in the database as primary key, who knows this kind of API? Any information is appreciated.
Printable View
I just want to get a unique int value to assign it to every record in the database as primary key, who knows this kind of API? Any information is appreciated.
Just make your own function that does it serially through a static int. Something like
Code:int ReturnUniqueInt()
{
static int counter = 0;
counter++;
return counter;
}
This method can not guarantee that every app-start we can get a unique int, but it show me a good hint. Thanks
If the purpose is to generate primary key in a database, you should use the "identity" property of your database. It will generate new unique keys itself at each insert...
If you use ORACLE there is SEQUENCES in it.
If you want to be database independent there is no other way then creating a counter table in the database:
create table my_counters (
tablecode int,
currentvalue int
)
Now insert a record for your table which needs a unique id:
insert into my_counters value (1, 0)
Then you can query the database for a unique id:
begin transaction
update my_counters set currentvalue=currentvalue+1 where tablecode=1
select countervalue from my_counters where tablecode=1
commit transaction
This solution not good for multi-thread application
use CriticalSection to modified it.
int ReturnUniqueInt()
{
static int counter = 0;
counter++;
return counter;
}
Hi, and what about - at first read by sql question max of this value from table. Then increment it and use it for create new record.
Alex.
That's not possible:Quote:
Originally posted by AlexEg
Hi, and what about - at first read by sql question max of this value from table. Then increment it and use it for create new record.
First - try to formulate the SQL commands. It will be something like
begin transaction
select max(...) from ...
insert into values (..., ...)
end transaction
How to put the max value into the insert statement?
And there is no valid SQL command like
insert into values (select max(...) from ..., ...)
Second - you will have the problem that multiple clients can read the same max value before one of the clients can do the insert. A select will not lock the row.
2alpha137:
You very very mistake. The following instruction do this
Code:insert into [table1]([field1]) select max([field2]) from [table2]
Oh, really?Quote:
Originally posted by alexey_1979
2alpha137:
You very very mistake. The following instruction do this
Code:insert into [table1]([field1]) select max([field2]) from [table2]
I agree that your statement will run against Microsoft databases (MS SQL Server, Access, ...). It may run against Oracle but I'm not sure. But I would be totally surprised if it would run against Informix or DB2.