How can I get the identity generated by the SQL SERVER when I insert a record

Z

zjs

for example
I can solve it in a single user.
_RecordsetPtr pR;
pConnection->Execute("Insert into TTest(nTest)
VALUES(100)"),&recordAffect,adCmdText);
pConnection->Execute("Select SCOPE_IDENTITY AS 'ID'
"),&recordAffect,adCmdText);
_variant_t vIndex = (LONG)0;
_variant_t vCount = pR->GetCollect("ID");

I get the identity in "vCount" successful.
but in multiusers. what should I do???any good advice?
 
C

Carl Daniel [VC++ MVP]

zjs said:
for example
I can solve it in a single user.
_RecordsetPtr pR;
pConnection->Execute("Insert into TTest(nTest)
VALUES(100)"),&recordAffect,adCmdText);
pConnection->Execute("Select SCOPE_IDENTITY AS 'ID'
"),&recordAffect,adCmdText);
_variant_t vIndex = (LONG)0;
_variant_t vCount = pR->GetCollect("ID");

I get the identity in "vCount" successful.
but in multiusers. what should I do???any good advice?

Not really a C++ question, but...

The solution is to perform both the insert and the retreival of
scope_identity in a single batch (i.e. present SQL server with both pieces
of text - the insert and the select - in a single call to Execute). You
could also make a stored proc in your database that does the insert followed
by the select and invoke that from your C++ code. Many database designers
would argue that that's the "correct" way.

See http://msdn.microsoft.com/en-us/library/ms190315.aspx for details on
SCOPE_IDENTITY.

-cd
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top