472,791 Members | 1,120 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,791 software developers and data experts.

SCOPE_IDENTITY won't return correct value, but @@IDENTITY does

Hi all,
I have the following codes, but SCOPE_IDENTITY() just returns NULL to
me. If I comment out SCOPE_IDENTITY() line and run @@IDENTITY line, it works
fine!! Since I have a trigger on the table, I have to use SCOPE_IDENTITY().
Any ideas?

SqlConnection conn = new SqlConnection(connectionString);
conn.Open();

//Create the dataadapter
SqlDataAdapter da = new SqlDataAdapter();

//Assign the connection & Create and execute the Insert Command
da.InsertCommand = new SqlCommand("insert into table1......");
da.InsertCommand.Connection = conn;

da.InsertCommand.ExecuteNonQuery();

//Create,assign and Execute the Identity statement
da.SelectCommand = new SqlCommand("SELECT SCOPE_IDENTITY()",
da.InsertCommand.Connection);
//da.SelectCommand = new SqlCommand("SELECT @@IDENTITY",
da.InsertCommand.Connection);
int intID = Convert.ToInt32(da.SelectCommand.ExecuteScalar());
conn.Close();
return(intID);

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
Nov 17 '05 #1
6 6352
IMO the problem is that you are running those two statement separately i.e.
the global @@IDENTITY still returns a (wrong) value but SCOPE_IDENTITY is
not in the same scope and returns NULL.

Sending INSERT/SELECT in the same round trip should solve the problem...
--

Patrice

"Hardy Wang" <ha*******@hotmail.com> a écrit dans le message de
news:eW**************@TK2MSFTNGP15.phx.gbl...
Hi all,
I have the following codes, but SCOPE_IDENTITY() just returns NULL to
me. If I comment out SCOPE_IDENTITY() line and run @@IDENTITY line, it works fine!! Since I have a trigger on the table, I have to use SCOPE_IDENTITY(). Any ideas?

SqlConnection conn = new SqlConnection(connectionString);
conn.Open();

//Create the dataadapter
SqlDataAdapter da = new SqlDataAdapter();

//Assign the connection & Create and execute the Insert Command
da.InsertCommand = new SqlCommand("insert into table1......");
da.InsertCommand.Connection = conn;

da.InsertCommand.ExecuteNonQuery();

//Create,assign and Execute the Identity statement
da.SelectCommand = new SqlCommand("SELECT SCOPE_IDENTITY()",
da.InsertCommand.Connection);
//da.SelectCommand = new SqlCommand("SELECT @@IDENTITY",
da.InsertCommand.Connection);
int intID = Convert.ToInt32(da.SelectCommand.ExecuteScalar());
conn.Close();
return(intID);

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy

Nov 17 '05 #2
If I drop trigger, @@IDENTITY returns the correct value.

I think I re-use the same connection to run SCOPE_IDENTITY by
da.SelectCommand = new SqlCommand("SELECT SCOPE_IDENTITY()",
da.InsertCommand.Connection). I pass the existing connection object back to
this command again, in this case are these two SQL statements in the same
scope?
"Patrice" <no****@nowhere.com> wrote in message
news:eq**************@tk2msftngp13.phx.gbl...
IMO the problem is that you are running those two statement separately
i.e.
the global @@IDENTITY still returns a (wrong) value but SCOPE_IDENTITY is
not in the same scope and returns NULL.

Sending INSERT/SELECT in the same round trip should solve the problem...
--

Patrice

"Hardy Wang" <ha*******@hotmail.com> a écrit dans le message de
news:eW**************@TK2MSFTNGP15.phx.gbl...
Hi all,
I have the following codes, but SCOPE_IDENTITY() just returns NULL to
me. If I comment out SCOPE_IDENTITY() line and run @@IDENTITY line, it

works
fine!! Since I have a trigger on the table, I have to use

SCOPE_IDENTITY().
Any ideas?

SqlConnection conn = new SqlConnection(connectionString);
conn.Open();

//Create the dataadapter
SqlDataAdapter da = new SqlDataAdapter();

//Assign the connection & Create and execute the Insert Command
da.InsertCommand = new SqlCommand("insert into table1......");
da.InsertCommand.Connection = conn;

da.InsertCommand.ExecuteNonQuery();

//Create,assign and Execute the Identity statement
da.SelectCommand = new SqlCommand("SELECT SCOPE_IDENTITY()",
da.InsertCommand.Connection);
//da.SelectCommand = new SqlCommand("SELECT @@IDENTITY",
da.InsertCommand.Connection);
int intID = Convert.ToInt32(da.SelectCommand.ExecuteScalar());
conn.Close();
return(intID);

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy


Nov 17 '05 #3
Some points here:

1. What are you trying to do with the DataAdapter here? DataAdapter is used
as bridge between DataSet(DataTable) and data store. If you simply want to
execute some SQL code (dynamic SQL or store procedure), just use SqlCommand,
no need to put Command into a DataAdapter.

2. From what I saw, you are inserting record and then want to get the
record's ID, which is Identity column in database. Since you use SQL Server,
the better approach is to use SqlCommand to pass parameters to a stored
procedure, which uses those parameters to insert a new record and return the
record ID. This way, your app only need one round trip to the Sql Server,
instead of two as your code does, one for inserting and one for retrieving
(and retriving possible wrong ID, as you are experiencing).

3. SCOPE_IDENTITY(), as its name implies, only gets the newly generated ID
in certain scope. In your case, you try to call it in a seperate trip to the
SQL Server, of course you get nul, because the inserting execution has been
done in previour trip and out of SCOPE already.

4. Yes, @@Identity MAY give you correct ID, as you have seen. But it is not
reliable, especially in you case (tow seperate trips to get the ID), because
after the execution of inserting and before your next call to @@Identity,
other user may also insert a new record. If so, your second trip to call
@Identity will definitely give you wrong ID.

So, as I mentioned, you'd better use SP to do the inserting and returning ID
in one shot, like this

CREATE PROCEDURE InsertNewRecord
(
@ID int OUTPUT
@Col1 ..
@Col2..
...
)
AS
INSERT INTO TheTable (Col1,Col2...) VALUES (@Col1,@Col2...)
SET @ID=SCOPE_IDENTITY()
RETURN

The in your app, you just create a SlqCommand and populate its Parameters
collection and call Command.ExcuteNonQuery(). Then retrieve ID from output
parameter:

int ID=(int)cmd.Parameters["@ID"].Value;
"Hardy Wang" <ha*******@hotmail.com> wrote in message
news:eW**************@TK2MSFTNGP15.phx.gbl...
Hi all,
I have the following codes, but SCOPE_IDENTITY() just returns NULL to
me. If I comment out SCOPE_IDENTITY() line and run @@IDENTITY line, it works fine!! Since I have a trigger on the table, I have to use SCOPE_IDENTITY(). Any ideas?

SqlConnection conn = new SqlConnection(connectionString);
conn.Open();

//Create the dataadapter
SqlDataAdapter da = new SqlDataAdapter();

//Assign the connection & Create and execute the Insert Command
da.InsertCommand = new SqlCommand("insert into table1......");
da.InsertCommand.Connection = conn;

da.InsertCommand.ExecuteNonQuery();

//Create,assign and Execute the Identity statement
da.SelectCommand = new SqlCommand("SELECT SCOPE_IDENTITY()",
da.InsertCommand.Connection);
//da.SelectCommand = new SqlCommand("SELECT @@IDENTITY",
da.InsertCommand.Connection);
int intID = Convert.ToInt32(da.SelectCommand.ExecuteScalar());
conn.Close();
return(intID);

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy

Nov 17 '05 #4
Yes, @@IDENTITY is global but takes always the very last ID (i.e. this is
the one used by your trigger).

It just means you run them on the same connection. The "scope" is likely
narrower than that (and in particular IMO the scope doesn't cross batches).
Have you tried my suggestion ?

--
Patrice

"Hardy Wang" <ha*******@hotmail.com> a écrit dans le message de
news:O0**************@TK2MSFTNGP12.phx.gbl...
If I drop trigger, @@IDENTITY returns the correct value.

I think I re-use the same connection to run SCOPE_IDENTITY by
da.SelectCommand = new SqlCommand("SELECT SCOPE_IDENTITY()",
da.InsertCommand.Connection). I pass the existing connection object back to this command again, in this case are these two SQL statements in the same
scope?
"Patrice" <no****@nowhere.com> wrote in message
news:eq**************@tk2msftngp13.phx.gbl...
IMO the problem is that you are running those two statement separately
i.e.
the global @@IDENTITY still returns a (wrong) value but SCOPE_IDENTITY is not in the same scope and returns NULL.

Sending INSERT/SELECT in the same round trip should solve the problem...
--

Patrice

"Hardy Wang" <ha*******@hotmail.com> a écrit dans le message de
news:eW**************@TK2MSFTNGP15.phx.gbl...
Hi all,
I have the following codes, but SCOPE_IDENTITY() just returns NULL to me. If I comment out SCOPE_IDENTITY() line and run @@IDENTITY line, it

works
fine!! Since I have a trigger on the table, I have to use

SCOPE_IDENTITY().
Any ideas?

SqlConnection conn = new SqlConnection(connectionString);
conn.Open();

//Create the dataadapter
SqlDataAdapter da = new SqlDataAdapter();

//Assign the connection & Create and execute the Insert Command
da.InsertCommand = new SqlCommand("insert into table1......");
da.InsertCommand.Connection = conn;

da.InsertCommand.ExecuteNonQuery();

//Create,assign and Execute the Identity statement
da.SelectCommand = new SqlCommand("SELECT SCOPE_IDENTITY()",
da.InsertCommand.Connection);
//da.SelectCommand = new SqlCommand("SELECT @@IDENTITY",
da.InsertCommand.Connection);
int intID = Convert.ToInt32(da.SelectCommand.ExecuteScalar());
conn.Close();
return(intID);

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy



Nov 17 '05 #5
I appended ";Select Scope_Identity()" to end of my insert statement, and
ran with "ExecuteScalar", then I got what I need.

Thanks a lot!

"Patrice" <no****@nowhere.com> wrote in message
news:OV**************@TK2MSFTNGP10.phx.gbl...
Yes, @@IDENTITY is global but takes always the very last ID (i.e. this is
the one used by your trigger).

It just means you run them on the same connection. The "scope" is likely
narrower than that (and in particular IMO the scope doesn't cross
batches).
Have you tried my suggestion ?

--
Patrice

"Hardy Wang" <ha*******@hotmail.com> a écrit dans le message de
news:O0**************@TK2MSFTNGP12.phx.gbl...
If I drop trigger, @@IDENTITY returns the correct value.

I think I re-use the same connection to run SCOPE_IDENTITY by
da.SelectCommand = new SqlCommand("SELECT SCOPE_IDENTITY()",
da.InsertCommand.Connection). I pass the existing connection object back

to
this command again, in this case are these two SQL statements in the same
scope?
"Patrice" <no****@nowhere.com> wrote in message
news:eq**************@tk2msftngp13.phx.gbl...
> IMO the problem is that you are running those two statement separately
> i.e.
> the global @@IDENTITY still returns a (wrong) value but SCOPE_IDENTITY is > not in the same scope and returns NULL.
>
> Sending INSERT/SELECT in the same round trip should solve the
> problem...
> --
>
> Patrice
>
> "Hardy Wang" <ha*******@hotmail.com> a écrit dans le message de
> news:eW**************@TK2MSFTNGP15.phx.gbl...
>> Hi all,
>> I have the following codes, but SCOPE_IDENTITY() just returns NULL to >> me. If I comment out SCOPE_IDENTITY() line and run @@IDENTITY line, it
> works
>> fine!! Since I have a trigger on the table, I have to use
> SCOPE_IDENTITY().
>> Any ideas?
>>
>> SqlConnection conn = new SqlConnection(connectionString);
>> conn.Open();
>>
>> //Create the dataadapter
>> SqlDataAdapter da = new SqlDataAdapter();
>>
>> //Assign the connection & Create and execute the Insert Command
>> da.InsertCommand = new SqlCommand("insert into table1......");
>> da.InsertCommand.Connection = conn;
>>
>> da.InsertCommand.ExecuteNonQuery();
>>
>> //Create,assign and Execute the Identity statement
>> da.SelectCommand = new SqlCommand("SELECT SCOPE_IDENTITY()",
>> da.InsertCommand.Connection);
>> //da.SelectCommand = new SqlCommand("SELECT @@IDENTITY",
>> da.InsertCommand.Connection);
>> int intID = Convert.ToInt32(da.SelectCommand.ExecuteScalar());
>> conn.Close();
>> return(intID);
>>
>> --
>> WWW: http://hardywang.1accesshost.com
>> ICQ: 3359839
>> yours Hardy
>>
>>
>
>



Nov 17 '05 #6
Hey Hardy,

Yeah this is that one odd case where you may need to use @@IDENTITY instead
of SCOPE_IDENTITY (because of scope - I haven't seen your stored procs, but
I bet that is the reason).

Anyhow, just put a SET NOCOUNT OFF and SET NOCOUNT ON in your trigger, and
@@IDENTITY will give you the correct keys.

- Sahil Malik [MVP]
ADO.NET 2.0 book -
http://codebetter.com/blogs/sahil.ma.../13/63199.aspx
----------------------------------------------------------------------------

"Hardy Wang" <ha*******@hotmail.com> wrote in message
news:eW**************@TK2MSFTNGP15.phx.gbl...
Hi all,
I have the following codes, but SCOPE_IDENTITY() just returns NULL to
me. If I comment out SCOPE_IDENTITY() line and run @@IDENTITY line, it
works fine!! Since I have a trigger on the table, I have to use
SCOPE_IDENTITY().
Any ideas?

SqlConnection conn = new SqlConnection(connectionString);
conn.Open();

//Create the dataadapter
SqlDataAdapter da = new SqlDataAdapter();

//Assign the connection & Create and execute the Insert Command
da.InsertCommand = new SqlCommand("insert into table1......");
da.InsertCommand.Connection = conn;

da.InsertCommand.ExecuteNonQuery();

//Create,assign and Execute the Identity statement
da.SelectCommand = new SqlCommand("SELECT SCOPE_IDENTITY()",
da.InsertCommand.Connection);
//da.SelectCommand = new SqlCommand("SELECT @@IDENTITY",
da.InsertCommand.Connection);
int intID = Convert.ToInt32(da.SelectCommand.ExecuteScalar());
conn.Close();
return(intID);

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy

Nov 17 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Richard Golebiowski | last post by:
I have been trying to figure this out for quite some time and cannot find any examples in VB.Net or in VB that work correctly. I am working on an application where I want the user to be able to...
6
by: michael | last post by:
Below is a simplified version of table cell mouseover script, running separate from the HTML code, that was posted on this group yesterday: var d=document, td; function mover(){...
2
by: eight02645999 | last post by:
hi i use odbc to update a table in a database but i always get return value of -1 even though i tried to return an integer. the table is updated though .... sql = """ update table set column =...
3
by: Oberon | last post by:
How do I deal with this? I am getting an error for each get in the Game class (see code below). In the simplified example below I have reduced this to just 3 fields, one which can be NULL. I...
7
by: JerryW | last post by:
I just reinstalled .NET 2003 (after repeated attempts to get ASP.NET Web Applications to work). I first did a complete uninstall of .NET 2003, .NET Framework 1.1, and IIS. I also completely deleted...
2
by: Jim Langston | last post by:
I'm a little confused. I have a class function declared like: const CItem& operator << (const std::string &sIn); Which I use like this: CItem Item; Item <<...
0
by: Eric | last post by:
I'm trying to run a C# web service that I ported from VS 2003 to VS 2005. I'm unable to run it, I see: Failed to execute the request because the ASP.NET process identity does not have read...
5
by: kenneth6 | last post by:
int Class::function() { if(a>b) { if(c==1) { if(d==2) { return 2; }
2
by: Mohammadtaqi | last post by:
warning C4715: 'Pow' : not all control paths return a value warning C4715: 'Sery' : not all control paths return a value #include "stdafx.h" #include <iostream> double Pow(double x, int n)...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: lllomh | last post by:
How does React native implement an English player?
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.