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

  • Thread starter Thread starter zjs
  • Start date Start date
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?
 
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
 
Back
Top