Showing posts with label identity. Show all posts
Showing posts with label identity. Show all posts

Monday, March 19, 2012

get value of rowguidcol from last inserted row

How would I get the value of a ROWGUID column of the row I just inserted? (like using @.@.identity for an identity column.)

Thanks!I think that the only way to accomplish this is to use the NEWID() function before your INSERT statement to explicitly assign the value.

David Penton has a stored proceudre which explains this technique:A example of returning a guid as an "Identity" in ADO

Terri|||Why would you like this?

Why do you not create the GUID on the client side?

GUID's are defiend to be unique wherever you create them. There is - contrary to identity fields - no need to have the server define them.

This is the beauty of them - I know them when the object they mark (if they are the PK) is created, not once it is inserted into the database.|||I would like this because I know, like, and respect David Penton.

Yes, having the client create the GUID would be another way to go. I don't see a real advantage of creating the GUID on the client side, however.

To me, a row identifier is something that SQL needs and cares about, and the client couldn't care less about. So why would the client have the job of creating it?

Maybe you can explain further.

Terri|||::Why would you like this?

::Why do you not create the GUID on the client side?

This is what I ended up doing.|||::To me, a row identifier is something that SQL needs and cares about, and the client couldn't
::care less about.

In this casse, why does teh client need to know at all?

If the ROWGUID is simply used as replication identifier, for example, the client can be "ignorant" and just ignore it.

Obviously, for some reason, this is not the case - the client needs to know.

And then, i f it needs to know, and inserts the row anyway, it can also determine it.

::So why would the client have the job of creating it?

Because the client inserts the row and obviously does something with the id, otherwise it would not requrey for it.

I assume it is some sort of primary key, too.

And here is is much easier to work with a guid the moment you create the row, instead of inserting it later.

Get Value of IDENTITY

Hi,
I need get value of IDENTITY column after a insert (of the inserted item),
hava way to do this automatic, or same function that do this?
ThanksCheck out SCOPE_IDENTITY() in the BOL.
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com
"ReTF" <re.tf@.newsgroup.nospam> wrote in message
news:%23vrhmlOxFHA.3864@.TK2MSFTNGP12.phx.gbl...
> Hi,
> I need get value of IDENTITY column after a insert (of the inserted item),
> hava way to do this automatic, or same function that do this?
> Thanks
>|||3 ways
@.@.IDENTITY
IDENT_CURRENT
SCOPE_IDENTITY()
Read BOL
Rakesh
"ReTF" wrote:

> Hi,
> I need get value of IDENTITY column after a insert (of the inserted item),
> hava way to do this automatic, or same function that do this?
> Thanks
>
>|||@.@.Identity global variable should hold the value of the last generate
during an insert.
Martin
ReTF wrote:
> Hi,
> I need get value of IDENTITY column after a insert (of the inserted item),
> hava way to do this automatic, or same function that do this?
> Thanks
>|||You should use SCOPE_IDENTITY() because it is possible for a trigger to also
insert a row and generate an identity value. @.@.IDENTITY returns the last
IDENTITY value generated. IDENT_CURRENT returns the last generated IDENTITY
value for a table, but it's possible in a concurrent environment for
IDENT_CURRENT to change between the time that a row is inserted and the time
that IDENT_CURRENT is called. The best solution, therefore, is to use
SCOPE_IDENTITY() because it returns the last generated IDENTITY value within
the current scope, thus ignoring any IDENTITY values generated within
triggers.
"ReTF" <re.tf@.newsgroup.nospam> wrote in message
news:%23vrhmlOxFHA.3864@.TK2MSFTNGP12.phx.gbl...
> Hi,
> I need get value of IDENTITY column after a insert (of the inserted item),
> hava way to do this automatic, or same function that do this?
> Thanks
>

Friday, March 9, 2012

Get the ColumnName of the Identity in a Table

Hi,
I need to know the name of the Column which is the Identity of a Table.
Below is the query to what point I succeeded. But now I'm stuck.
This query returns all tables with an Identity-Column in a database, crossed
with ALL columns (obviously).
Any suggestions?
TIA,
Michael
SELECT INFORMATION_SCHEMA.TABLES.TABLE_CATALOG,
INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA,
INFORMATION_SCHEMA.TABLES.TABLE_NAME,
INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME,
IDENT_SEED(INFORMATION_SCHEMA.TABLES.TABLE_NAME) AS
IDENT_SEED, IDENT_INCR(INFORMATION_SCHEMA.TABLES.TABLE_NAME)
AS IDENT_INCR,
IDENT_CURRENT(INFORMATION_SCHEMA.TABLES.TABLE_NAME) AS IDENT_CURRENT
FROM INFORMATION_SCHEMA.TABLES INNER JOIN
INFORMATION_SCHEMA.COLUMNS ON
INFORMATION_SCHEMA.TABLES.TABLE_CATALOG =
INFORMATION_SCHEMA.COLUMNS.TABLE_CATALOG AND
INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA =
INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA AND
INFORMATION_SCHEMA.TABLES.TABLE_NAME =
INFORMATION_SCHEMA.COLUMNS.TABLE_NAME
WHERE (IDENT_SEED(INFORMATION_SCHEMA.TABLES.TABLE_NAME) IS NOT NULL)I think just found it:
SELECT TABLE_CATALOG,
TABLE_SCHEMA,
TABLE_NAME,
COLUMN_NAME,
IDENT_SEED(TABLE_NAME) AS IDENT_SEED,
IDENT_INCR(TABLE_NAME) AS IDENT_INCR,
IDENT_CURRENT(TABLE_NAME) AS IDENT_CURRENT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMNPROPERTY(OBJECT_ID(TABLE_NAME),COL
UMN_NAME,'IsIdentity')=1
I'm just not sure if this approach will work on Server 2005...
Michael|||How about this?
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMNPROPERTY(OBJECT_ID(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
AND TABLE_NAME = 'Orders'
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Michael Maes" <michael@.merlot.com> wrote in message
news:262D812C-5439-49F0-B6CA-C2B4511BF0FD@.microsoft.com...
> Hi,
> I need to know the name of the Column which is the Identity of a Table.
> Below is the query to what point I succeeded. But now I'm stuck.
> This query returns all tables with an Identity-Column in a database, cross
ed
> with ALL columns (obviously).
> Any suggestions?
> TIA,
> Michael
> SELECT INFORMATION_SCHEMA.TABLES.TABLE_CATALOG,
> INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA,
> INFORMATION_SCHEMA.TABLES.TABLE_NAME,
> INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME,
> IDENT_SEED(INFORMATION_SCHEMA.TABLES.TABLE_NAME) AS
> IDENT_SEED, IDENT_INCR(INFORMATION_SCHEMA.TABLES.TABLE_NAME)
> AS IDENT_INCR,
> IDENT_CURRENT(INFORMATION_SCHEMA.TABLES.TABLE_NAME) AS IDENT_CURRENT
> FROM INFORMATION_SCHEMA.TABLES INNER JOIN
> INFORMATION_SCHEMA.COLUMNS ON
> INFORMATION_SCHEMA.TABLES.TABLE_CATALOG =
> INFORMATION_SCHEMA.COLUMNS.TABLE_CATALOG AND
> INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA =
> INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA AND
> INFORMATION_SCHEMA.TABLES.TABLE_NAME =
> INFORMATION_SCHEMA.COLUMNS.TABLE_NAME
> WHERE (IDENT_SEED(INFORMATION_SCHEMA.TABLES.TABLE_NAME) IS NOT NULL)|||Hi Tibor,
Thanks for your reply.
Will this approach also be compatible with 2005?
Regards,
Michael
"Tibor Karaszi" wrote:

> How about this?
> SELECT *
> FROM INFORMATION_SCHEMA.COLUMNS
> WHERE COLUMNPROPERTY(OBJECT_ID(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
> AND TABLE_NAME = 'Orders'
>|||Yep. The purpose of info schema view is not only be stable across versions,
but also across
different DBMS vendors. They are defined in the ANSI SQL standard.
I just ran the query against 2005 April CTP, just to give it a spin...
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Michael Maes" <michael@.merlot.com> wrote in message
news:B85C547B-726F-47A7-84FE-70A0384314CE@.microsoft.com...
> Hi Tibor,
> Thanks for your reply.
> Will this approach also be compatible with 2005?
> Regards,
> Michael
> "Tibor Karaszi" wrote:
>|||Thanks Tibor,
Quite a relief :-)
Michael
"Tibor Karaszi" wrote:

> Yep. The purpose of info schema view is not only be stable across versions
, but also across
> different DBMS vendors. They are defined in the ANSI SQL standard.
> I just ran the query against 2005 April CTP, just to give it a spin...
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
>

Sunday, February 26, 2012

Get Scope Identity Value using ObjectDataSource and Vb.Net

Hi,

I have been trying to get the scope Identity after inserting a record using an ObjectDataSource.

I can't find what event, or how to get the value that the scope identity returns.

Here is my Sproc.

ALTER PROCEDUREdbo.[YourCompany_LanCustomer_Insert]

(

@.DNNUserIDint,

@.FirstNamenvarchar(50),

@.LastNamenvarchar(50),

@.Addressnvarchar(50),

@.Address2nvarchar(50),

@.Citynvarchar(50),

@.Statenvarchar(50),

@.Zipnvarchar(50),

@.EmailAddressnvarchar(50),

@.PhoneNumbernvarchar(50),

@.CustomerIDint OUTPUT

)

AS

INSERT INTOYourCompany_LanCustomer

(DNNUserID, FirstName, LastName, Address, Address2, City, State, Zip, EmailAddress, PhoneNumber, DateEntered)

VALUES(@.DNNUserID, @.FirstName, @.LastName, @.Address, @.Address2, @.City, @.State, @.Zip, @.EmailAddress, @.PhoneNumber,getdate())

SET@.CustomerID =Scope_Identity()

RETURN

When I try to execute the stored procedure in Sql Manager I get the CustomerID Value, how do I get this value in the VB.Net code behind?

Any help is greatly appreciated.

In the Inserted event of the ObjectDataSource and you use the OutputParameters collection to get the value

Protected Sub ObjectDataSource1_Inserted(ByVal senderAs Object,ByVal eAs ObjectDataSourceStatusEventArgs)Dim _customerIdAs Integer =CInt(e.OutputParameters("@.CustomerID"))End Sub

Thanks

-Mark post(s) as "Answer" that helped you

|||

You'll get the collection of the insert parameters for the data source. You can retrieve the value of any parameter using yourDataSourceID.InsertParameters("parameterName"). You haven't explained how you're executing the stored procedure here. If possible post the aspx page code so that we can know how you've setup the data source.

|||

Now I'm lost, do I get the Scope Identity at the iteminserting or the iteminserted. I tried the first sample and get a parameter is not equal error.

Here is my ascx (I'm using dotnetnuke) for the objectDataSource.

<asp:ObjectDataSourceID="ObjectDataSource_Customer"runat="server"TypeName="YourCompany.Modules.Lan.LanCustomerController"SelectMethod="LanCustomer_GetCustomers"DataObjectTypeName="YourCompany.Modules.Lan.LanCustomerInfo"DeleteMethod="LanCustomer_Delete"OldValuesParameterFormatString="original_{0}"InsertMethod="LanCustomer_Insert">

</asp:ObjectDataSource>

here is the code behind (vb.net) that I am using on insert:

ProtectedSub NewItem(ByVal senderAsObject,ByVal eAs System.Web.UI.WebControls.FormViewInsertEventArgs)Handles CustomerFormView.ItemInserting

Try

e.Values.Item("CustomerId") = 0

If e.Values.Item("DNNUserID") ="-1"Then

e.Values.Item("DNNUserID") ="0"

Else

e.Values.Item("DNNUserID") = UserId

EndIf

If e.Values.Item("FirstName") =""Then

e.Values.Item("FirstName") = Null.NullString

EndIf

If e.Values.Item("LastName") =""Then

e.Values.Item("LastName") = Null.NullString

EndIf

If e.Values.Item("Address") =""Then

e.Values.Item("Address") = Null.NullString

EndIf

If e.Values.Item("Address2") =""Then

e.Values.Item("Address2") = Null.NullString

EndIf

If e.Values.Item("City") =""Then

e.Values.Item("City") = Null.NullString

EndIf

If e.Values.Item("State") =""Then

e.Values.Item("State") = Null.NullString

EndIf

If e.Values.Item("Zip") =""Then

e.Values.Item("Zip") = Null.NullString

EndIf

If e.Values.Item("EmailAddress") =""Then

e.Values.Item("EmailAddress") = Null.NullString

EndIf

If e.Values.Item("PhoneNumber") =""Then

e.Values.Item("PhoneNumber") = Null.NullString

EndIf

Catch exAs Exception

ProcessModuleLoadException(Me, ex)

EndTry

EndSub

The insert sproc worked before, I just can't get it to work now.

|||

Hi,

SET @.CustomerID = Scope_Identity()

From the code you provided, the @.CustomerID is an OUTPUT parameter you set, right?

And we assume that you are using SqlCommand to execute the stored procedure in your business object method, and then you can retrieve the OUTPUT parameter in stored procedure by declaring a SqlParameter which in an OUTPUT direction. Make your business object method return the parameter's value after you invoking ExecuteNonQuery() method.

And then, in ObjectDataSource1_Selected event, try to get the value from RetrunValue property of ObjectDataSourceStatusEventArgs.

Thanks.

|||

Nai-Dong Jin - MSFT:

you can retrieve the OUTPUT parameter in stored procedure by declaring a SqlParameter which in an OUTPUT direction. Make your business object method return the parameter's value after you invoking ExecuteNonQuery() method.

And then, in ObjectDataSource1_Selected event, try to get the value from RetrunValue property of ObjectDataSourceStatusEventArgs.

Why do we need to "RETURN" the "OUTPUT PARAMETER" ? Do you know that RETURN values and OUTPUT parameters are independent of each other and we could retrieve either "RETURN" value or "OUTPUT" parameter or both of them?

Note: I dont know how the thread was marked as "Answer"

Thanks

-Mark post(s) as "Answer" that helped you

|||

Hi e_screw,

First, I think you've misunderstood my words. What I suggest is to declare an OUTPUT parameter in his stored procedure, and then assign the parameter with the value of Identity_Scope(). That's all. What the rest is retrieving parameters in .NET application by using SqlParameter which is in OUTPUT direction. Is there anything wrong? In stored procedure level, can you find any words on "RETURN" in my previous post?

Make your business object method return the parameter's value after you invoking ExecuteNonQuery() method.

And since the original poster was using ObjectDataSource, so he must had invoked the ExecuteNonQuery() in the business object method, right? What I said "return the parameter's value" means return the value from the business method. In this stage, that's totally nothing related with the OUTPUT parameter in procs.

Now I'm lost,

Second,of course, you also can use "Return" to achieve that, but since the original poster was lost, kept asking against previous solution and no one followed up, I just provide another solution for him to refer.

So if you are able to help him further with your solution, I appreciate it. And it also can be beneficial to other community members reading the thread.

Thanks.

|||

This is your previous post:

Nai-Dong Jin - MSFT:

And then, in ObjectDataSource1_Selected event, try to get the value from RetrunValue property of ObjectDataSourceStatusEventArgs.

Last post:

Nai-Dong Jin - MSFT:

First, I think you've misunderstood my words. What I suggest is to declare an OUTPUT parameter in his stored procedure, and then assign the parameter with the value of Identity_Scope(). That's all. What the rest is retrieving parameters in .NET application by using SqlParameter which is in OUTPUT direction. Is there anything wrong? In stored procedure level, can you find any words on "RETURN" in my previous post?

In the first you said, get the value from the ReturnValue property , after assigning the value of OUTPUT parameters to it. In the second, you are just talking about OUTPUT parameters.

Have you had looked at the ObjectDataSourceStatusEventArgs, there is OutputParameters (which returns a collection of output parameters and their values) and a ReturnValue (which gets the return value returned by the business object, if any). Now read your replies again.

Note: Its not with my solution or your solution. Its all about a correct solution, which helps many other community members.

Thanks

|||

Hi,

To Dan5150,

Here's the sample code for you which describes the solution in my previous posts.

First, in your Procedure:

set ANSI_NULLSONset QUOTED_IDENTIFIERONgoALTER PROCEDURE [dbo].[ProcName]@.TOINSERTNVARCHAR(50),@.RESULTINT OUTPUT-- THE OUTPUT Parameter has been set as OUTPUTAS INSERT INTO MYTABLE(TOINSERT)VALUES (@.TOINSERT)SET@.RESULT = SCOPE_IDENTITY();

Second, here's the method in business object class:

Public Function BusinessMethod(ByVal TOINSERTAs String)As String Dim connAs String = ConfigurationManager.ConnectionStrings("SampleDbConnectionString").ConnectionStringDim myconnAs New SqlConnection(conn)Dim mycommAs New SqlCommand() mycomm.Connection = myconn mycomm.CommandText ="ProcName" mycomm.CommandType = CommandType.StoredProcedureDim sp1As New SqlParameter() sp1.ParameterName ="TOINSERT" sp1.Value = TOINSERTDim sp2As New SqlParameter() sp2.ParameterName ="RESULT"' This parameter has been set in OUTPUT direction sp2.Direction = ParameterDirection.Output sp2.Size = 4 sp2.SqlDbType = SqlDbType.Int mycomm.Parameters.Add(sp1) mycomm.Parameters.Add(sp2) myconn.Open() mycomm.ExecuteNonQuery() myconn.close()' Return the parameter in OUTPUT direction.Return sp2.Value.ToString()End Function

Third, you can get the value in Inserted event of ODS by accessing ReturnValue property.

Protected Sub ObjectDataSource1_Inserted(ByVal senderAs Object,ByVal eAs ObjectDataSourceStatusEventArgs) Response.Write(e.ReturnValue.ToString())' You can get the id of new inserted row here.End Sub

To e_screw,

Please read my codes, and especially the comment parts in bold. And let's back to your solution which given in the second post:


Protected Sub ObjectDataSource1_Inserted(ByVal sender As Object, ByVal e As ObjectDataSourceStatusEventArgs)
Dim _customerId As Integer = CInt(e.OutputParameters("@.CustomerID"))
End Sub

You can use OutputParameters collection to retrieve the value, while output parameters would be ByRef (out in C#) parameters.

But since the original poster hadn't posted out his business method signature, how can you make sure that he was declaring parameters that are passed to the business object method by reference? If the parameters was passed by val, how could he get the value in OutputParameters collection?

Thanks.


Friday, February 24, 2012

Get RecordNumber with output

Hi everyone,
How can get the record number as column with my query output.
I dont want to insert the values in #temp table with IDENTITY function.
Any other trick...
RiyazYou don't state which version of SQL Server you are using. If you are using SQL Server 2005 you can use the new ROW_NUMBER() (http://msdn2.microsoft.com/en-us/library/ms186734.aspx) function.|||You don't state which version of SQL Server you are using. If you are using SQL Server 2005 you can use the new ROW_NUMBER() (http://msdn2.microsoft.com/en-us/library/ms186734.aspx) function.

Sorry for that

I am using SQL Server 2000

Sunday, February 19, 2012

Get next unique ID from a table before insert @@identity / Sequence

How do I get the next int value for a column before I do an insert in
MY SQL Server 2000? I'm currently using Oracle sequence and doing
something like:

select seq.nextval from dual;

Then I do my insert into 3 different table all using the same uniqueID.

I can't use the @.@.identity function because my application uses a
connection pool and it's not garanteed that a connection won't be used
by another request so under a lot of load there could be major problems
and this doens't work:

insert into <table>;
select @.@.identity;

This doesn't work because the select @.@.identity might give me the value
of an insert from someone else's request.

Thanks,

BrentOn 16 Mar 2005 14:58:25 -0800, brent.ryan@.gmail.com wrote:

>How do I get the next int value for a column before I do an insert in
>MY SQL Server 2000? I'm currently using Oracle sequence and doing
>something like:
>select seq.nextval from dual;
>Then I do my insert into 3 different table all using the same uniqueID.
>I can't use the @.@.identity function because my application uses a
>connection pool and it's not garanteed that a connection won't be used
>by another request so under a lot of load there could be major problems
>and this doens't work:
>insert into <table>;
>select @.@.identity;
>This doesn't work because the select @.@.identity might give me the value
>of an insert from someone else's request.
>Thanks,
>Brent

Hi Brent,

Create a stored procedure that starts a transaction, inserts into the
first table, retrieves the identity value used (with SCOPE_IDENTITY, the
recommended method in SQL Server 2000), uses it to insert data into the
other two table, then commits the transaction (or rolls it back if
anything went wrong).

Calling the server three times for three inserts is not only incurring
the overhead of more roundtrips then necessary, you also run the risk of
getting corrupted data: if one insert fails and the others succeed,
you'll have incomplete data in your database. Always include related
modifications in a transaction. And if each call to the database can use
a different connection, then the complete operation, from start to end
of transaction, needs to be done in one call, as transactions are tied
to the connection.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||(brent.ryan@.gmail.com) writes:
> insert into <table>;
> select @.@.identity;
> This doesn't work because the select @.@.identity might give me the value
> of an insert from someone else's request.

No, @.@.identity is local to the connection, so it cannot be someone
else's value. Well, if you submit to queries and close your connection
in between, it won't work, but that would be poor practice anyway.

Hugo's suggestion of using a stored procedure is an excellent idea.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||On Thu, 17 Mar 2005 22:57:45 +0000 (UTC), Erland Sommarskog
<esquel@.sommarskog.se> wrote:

> (brent.ryan@.gmail.com) writes:
>> insert into <table>;
>> select @.@.identity;
>>
>> This doesn't work because the select @.@.identity might give me the value
>> of an insert from someone else's request.
>No, @.@.identity is local to the connection, so it cannot be someone
>else's value. Well, if you submit to queries and close your connection
>in between, it won't work, but that would be poor practice anyway.
>Hugo's suggestion of using a stored procedure is an excellent idea.

Excuse me for butting in here, Erland, but there is one 'little'
problem that I have found with @.@.IDENTITY that I can't see referred to
anywhere, and that anyone relying on it should know about, and that is
that @.@.IDENTITY can return unexpected values in certain circumstances.

In the supplied example:

insert into <table>
select @.@.identity

BEAWRE!
If there is a trigger fired during the insert on <table>, and the
trigger performs an insert itself, then @.@.IDENTITY will return the ID
from the Trigger's insert, not the <table> insert.

This caused me many to lose much more hair than I can afford!

It behaves this way in SQL Server 7, and 2000.

Here is a script to create a test data base:
(Make a new blank database, I called it "Test")

=============================
/****** Object: Table [dbo].[MainTable] Script Date: 18/03/2005
3:10:38 PM ******/
CREATE TABLE [dbo].[MainTable] (
[MainTableId] [int] IDENTITY (1, 1) NOT NULL ,
[LongName] [nvarchar] (255) NOT NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[TriggerTable] Script Date: 18/03/2005
3:10:39 PM ******/
CREATE TABLE [dbo].[TriggerTable] (
[TriggerTableId] [int] IDENTITY (666, 1) NOT NULL ,
[TriggerRowLongName] [nvarchar] (255) NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[TriggerTable] WITH NOCHECK ADD
CONSTRAINT [PK_TriggerTable] PRIMARY KEY CLUSTERED
(
[TriggerTableId]
) ON [PRIMARY]
GO
/****** Object: Stored Procedure dbo.Test_sp Script Date:
18/03/2005 3:10:39 PM ******/
CREATE PROCEDURE dbo.Test_sp
AS
INSERT INTO MainTable (LongName) VALUES ('TestLongName')
SELECT @.@.IDENTITY
GO
/****** Object: Trigger dbo.MainTable_Trigger1 Script Date:
18/03/2005 3:10:39 PM ******/
CREATE TRIGGER MainTable_Trigger1
ON dbo.MainTable
FOR INSERT,UPDATE,DELETE
AS
INSERT INTO TriggerTable (TriggerRowLongName) VALUES ('Stuff')
GO
=============================

Then, if one executes [Test_sp] in Query Analyser,

EXEC Test_sp

the returned @.@.IDENTITY is not 1, as you would expect, (this is ID of
the new MainTable row), but 666, which is the ID of the row inserted
via the trigger!
(I seeded this table's identity to begin at 666, in order to show up
clearly)

I would be interested if you were aware of this tiny problemette.|||Michael Gray (fleetg@.newsguy.spam.com) writes:
> Excuse me for butting in here, Erland, but there is one 'little'
> problem that I have found with @.@.IDENTITY that I can't see referred to
> anywhere, and that anyone relying on it should know about, and that is
> that @.@.IDENTITY can return unexpected values in certain circumstances.
> In the supplied example:
> insert into <table>
> select @.@.identity
> BEAWRE!
> If there is a trigger fired during the insert on <table>, and the
> trigger performs an insert itself, then @.@.IDENTITY will return the ID
> from the Trigger's insert, not the <table> insert.

Yes, this is a correct observation. For this reason, you should use
scope_identity() instead. This function was introduced in SQL 2000.

scope_identity() returns the most recently generated IDENTITY in the
current scope, that is a trigger, stored procedure, block of dynamic
SQL etc.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp