473,795 Members | 3,441 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Retrieving Identity Values after DetailsView Insert

I am struggling with trying to retrieve the value of an autoincrement identity field after a DetailsView Insert operation. The
DetailsView is bound to an SqlDataSource control.

So far as I can tell, nowhere in the arguments for either the Inserted event for the DetailsView or the Inserted event for the
SqlDataSource control is the value stored. Adding a dummy bound column for the identity field to the DetailsView doesn't work,
either.

All I can think of is to handle the SqlDataSource control's Inserted event and issue a separate SqlCommand to do a SELECT
SCOPE_IDENTITY( ).

There has to be a better way than that!

And if there isn't...someone at Microsoft needs to be taken to task for not thinking about how Insert operations against SQL
databases really ought to address the identity field issue.

- Mark
Mar 2 '07 #1
4 15018
Some further information...

Doing a separate SqlCommand to do a SELECT SCOPE_IDENTITY( ) AS newID doesn't work. It returns null. Same for SELECT @@IDENTITY AS
newID. I suspect that the first approach fails because SqlDataSource controls maintain their own SqlConnection, and so the SELECT
command is not in the same scope. I don't know why the second approach doesn't work.

Appending ;SET @newID = SCOPE_IDENTITY( ) to the SqlDataSource control's Insert query, and then specifying that @newID is an integer
parameter with an Output direction does work (i.e., you can retrieve the value of @newID from the Parameters collection of the
Command property within an event handler for the data source control's Inserted event.

But that seems like a dumb thing to have to do for every situation where I want to use a datasource control to insert a record into
a Sql database.

So I'd still like to hear of a more elegant answer...and if there isn't one, why in the world MS shipped something with such a huge
flaw.

- Mark
Mar 2 '07 #2
Hello Mark,

From your description, you're using SqlDataSource+D etailsView to insert
record into a certain table and the primary id of it is of autoincrement
column. therefore, you're wondering the proper way to let the DetailsView
or SqlDataSource get the autogenerated newid of the inserted record,
correct?

Based on my understanding, for such scenario, you should use the @@IDENTITY
or SCOPE_IDENTITY function(prefer red) to get the new generated autoid after
executing your insert statement. I would suggest you create a stored
procedure for such insert scenario. e.g.

=============== ==============
CREATE PROCEDURE [dbo].[usp_insert_item]
@name varchar(50),
@description varchar(300)
AS
BEGIN
insert items ([name],[description]) values(@name, @description)

declare @autoid bigint

set @autoid = SCOPE_IDENTITY( )

return @autoid
END
=============== ===============

Then, in your ASP.NET webpage's SqlDataSource, set insert commandtype as
"StoreProcedure " and statement set to the SP name. The IDE can help you
autogenerated the necessary parameter(inclu de the returnvalue parameter)
e.g.

=============== ======
............... .............
<InsertParamete rs>
<asp:Paramete r Direction="Retu rnValue" Name="RETURN_VA LUE"
Type="Int64" />
<asp:Paramete r Name="name" Type="String" />
<asp:Paramete r Name="descripti on" Type="String" />
</InsertParameter s>

</asp:SqlDataSour ce>
=============== ====

Thus, you can use the "SqlDataSource. Inserted" event to get the return
value from the called store procedure:

=============== =============== ======
protected void SqlDataSource1_ Inserted(object sender,
SqlDataSourceSt atusEventArgs e)
{

foreach (DbParameter param in e.Command.Param eters)
{
Response.Write( "<br/>" + param.Parameter Name + ": " +
param.Direction );
}

Response.Write( "<br/>autoid: " +
e.Command.Param eters["@RETURN_VA LUE"].Value);
}
===============

Also, instead of returnvalue, you can explicitly declare an output
parameter for your storeprocedure and use output parameter to get the auto
generated id.

Hope this helps.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

=============== =============== =============== =====

Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.

=============== =============== =============== =====

This posting is provided "AS IS" with no warranties, and confers no rights.

Mar 5 '07 #3
Steven,

That's esentially what I figured out: you have to include a "call" to SCOPE_IDENTITY( ) in the Insert command, either through a sproc
(as in your example) or by manually changing the data source control's insert query (which is what I'm doing, because I don't like
littering my database with dozens of little sprocs).

But the real question is, why do I have to do this in the first place? It shouldn't come as a suprise that when a row gets inserted
into a table with an identity field the caller will want to know the value of the new identity field. I think this is a flaw in the
code generator for the SqlDataSource control.

- Mark
Mar 5 '07 #4
Thanks for your reply Mark,

Yes, so far for those autogenerated ID, SQL Server won't return it
automaticaly since standard insert SQL statement doesn't contains
additional output resultset. We need to use additional query to retrieve
the @@IDENTITY or SCOPE_IDENTITY value. This also helps make the insert
command behave consistent between normal table(without using auto increated
id column) and table that use auto generated id column. Also, for
SqlDataSource control, since it currently generate only single insert
statement and do not automatically call any additional script to retrieve
identity value.

Anyway, you're welcome to submit such request for the SqlDataSource control
or its designer code generate:

http://connect.microsoft.com/feedbac...spx?SiteID=210
Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead
This posting is provided "AS IS" with no warranties, and confers no rights.

Mar 7 '07 #5

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

Similar topics

3
9766
by: Justin | last post by:
I have created a dataset with two tables and an insert command, I need to be able to retreive the Key Identity after inserting into table "A" for use in table "B". Should I use ExecuteScalar() or is there a better solution? Thanks, Justin.
0
1104
by: cjbland | last post by:
First off I apologize if this has been discussed before, I'm not certain how to search for what I'm looking for so I figured I'd throw this out there and see what I got. I am working with a DetailsView (Insert mode) in ASP.NET 2.0 and one of the fields I give a default value. <asp:DetailsView ....> <asp:TemplateField HeaderText="Date Entered" SortExpression="d_entered">
17
2704
by: Rico | last post by:
Hello, I am in the midst of converting an Access back end to SQL Server Express. The front end program (converted to Access 2003) uses DAO throughout. In Access, when I use recordset.AddNew I can retrieve the autonum value for the new record. This doesn't occur with SQL Server, which of course causes an error (or at least in this code it does since there's an unhandled NULL value). Is there any way to retrieve this value when I add a...
3
2852
by: Susanne Klemm | last post by:
Hello! I use a procedure to insert a new row into a table with an identity column. The procedure has an output parameter which gives me the inserted identity value. This worked well for a long time. Now the identity value is over 700.000 and I get errors whiles retrieving the inserted identitiy value. If I delete rows and reset the identity everything works well again. So I think it is a data type problem. My Procedure:
8
9259
by: Dave | last post by:
I have a form with a label that should show an invoice number. The invoice number should be generated by sql Server using an autoincremented technique. However, after reading several articles, it seems that I can only retrieve this value after an INSERT has been done in the database. I want to find out what this autoincremented before an insertion.-- L. A. Jones
15
3537
by: gunnar.sigurjonsson | last post by:
I´m having some problem retrieving identity value from my newly inserted row into a view. I have two tables T1 and T2 which I define as following CREATE TABLE T1 ( id BIGINT GENERATED ALWAYS AS IDENTITY ( START WITH 1
9
5638
by: vertigo262 | last post by:
Hello All, I am trying to create an insert stored procedure with an @@identity output. need help This didn't seem dificult when I attempted it, but I can't for the life of me get the identity returned. if anyone knows what I am doing wrong I would appreciate any help.
2
1257
by: siddu57 | last post by:
I have 2 tables - tblOrders and tblOrderDetails. Every time an order is placed, 2 INSERT statements are executed. The first one enters the general order and customer information in the tblOrders table: INSERT INTO tblOrders (custname, custdetails, orderdate) VALUES (@custname, @custdetails, @orderdate) The primary key in this table is OrderID which is an Identity column. This is the foreign key in the tblOrderDetails table. I'm trying...
0
3036
by: Frank Swarbrick | last post by:
So we're trying to decide if it's better to use IDENTITY columns or sequences to create a surrogate key as the primary key for our tables. I kind of like the identity column, because it's more 'tightly integrated' in to the table. With a sequence you have to make sure that each application that inserts records uses the same sequence. (Probably not likely that it wouldn't, but...) One thing where it seems like a SEQUENCE would be...
0
9519
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10214
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10164
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10001
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9042
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.