473,738 Members | 11,146 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Retrieving Record Key while creating the record.

Using SQL server and VS.NET with ASP.NET/C# how can I retrieve the Key ID of
a record right after creating that record in the same event? Do I need to
close and reopen the connection and requery?

Thanks, Justin.
Nov 18 '05 #1
4 1274
"INSERT INTO BLAH VALUES(1,2,3,4) ; SELECT @@IDENTITY;"

int key = Convert.ToInt32 (command.Execut eScalar());

Karl

--
MY ASP.Net tutorials
http://www.openmymind.net/
"Justin" <Ju****@discuss ions.microsoft. com> wrote in message
news:62******** *************** ***********@mic rosoft.com...
Using SQL server and VS.NET with ASP.NET/C# how can I retrieve the Key ID of a record right after creating that record in the same event? Do I need to
close and reopen the connection and requery?

Thanks, Justin.

Nov 18 '05 #2
Hi Justin,

You'll want to use ExecuteScalar() as shown in this article about one third
of the way down:

http://dotnetadvisor.net/doc/13279

Here's the relevant VB code:

<%@ import Namespace="Syst em.Data" %>
<%@ import Namespace="Syst em.Data.SqlClie nt" %>

<html>

<script language="VB" runat="server">

Sub Page_Load(Sourc e as Object, E as EventArgs)

Dim dbConn As SqlConnection

' Create a new connection object pointing to
the database
dbConn = New SqlConnection(" server=.;uid=sa ;pwd=
;database=North wind")

Dim dbComm As New SqlCommand()
dbComm.Connecti on = dbConn
dbComm.CommandT ype = CommandType.Tex t
dbComm.CommandT ext = "INSERT INTO Categories
(CategoryName, Description) " & _
"VALUES ('Guitars','Her e you can find just the " & _
"guitar you looked for'); SELECT @@IDENTITY As 'Identity'"
Dim iID As Integer

Try
dbConn.Open()
iID = dbComm.ExecuteS calar()
Catch ex As Exception
Response.Write( ex.Message)
Response.End
Finally
If dbConn.State = ConnectionState .Open Then
dbConn.Close()
End If
End Try

Response.Write( "The ID of the new record is: "
& iID.ToString())

End Sub

</script>
</html>

"Justin" wrote:
Using SQL server and VS.NET with ASP.NET/C# how can I retrieve the Key ID of
a record right after creating that record in the same event? Do I need to
close and reopen the connection and requery?

Thanks, Justin.

Nov 18 '05 #3
Ken ur all over me like a fat kid on a smarties today!

'tis best to cint dbComm.ExecuteS calar() and turn option strict on though :P

Karl
--
MY ASP.Net tutorials
http://www.openmymind.net/
"Ken Cox [Microsoft MVP]" <BA************ @sympatico.ca> wrote in message
news:4B******** *************** ***********@mic rosoft.com...
Hi Justin,

You'll want to use ExecuteScalar() as shown in this article about one third of the way down:

http://dotnetadvisor.net/doc/13279

Here's the relevant VB code:

<%@ import Namespace="Syst em.Data" %>
<%@ import Namespace="Syst em.Data.SqlClie nt" %>

<html>

<script language="VB" runat="server">

Sub Page_Load(Sourc e as Object, E as EventArgs)

Dim dbConn As SqlConnection

' Create a new connection object pointing to
the database
dbConn = New SqlConnection(" server=.;uid=sa ;pwd=
;database=North wind")

Dim dbComm As New SqlCommand()
dbComm.Connecti on = dbConn
dbComm.CommandT ype = CommandType.Tex t
dbComm.CommandT ext = "INSERT INTO Categories
(CategoryName, Description) " & _
"VALUES ('Guitars','Her e you can find just the " & _
"guitar you looked for'); SELECT @@IDENTITY As 'Identity'"
Dim iID As Integer

Try
dbConn.Open()
iID = dbComm.ExecuteS calar()
Catch ex As Exception
Response.Write( ex.Message)
Response.End
Finally
If dbConn.State = ConnectionState .Open Then
dbConn.Close()
End If
End Try

Response.Write( "The ID of the new record is: "
& iID.ToString())

End Sub

</script>
</html>

"Justin" wrote:
Using SQL server and VS.NET with ASP.NET/C# how can I retrieve the Key ID of a record right after creating that record in the same event? Do I need to close and reopen the connection and requery?

Thanks, Justin.

Nov 18 '05 #4
Thanks for the help!

"Justin" wrote:
Using SQL server and VS.NET with ASP.NET/C# how can I retrieve the Key ID of
a record right after creating that record in the same event? Do I need to
close and reopen the connection and requery?

Thanks, Justin.

Nov 18 '05 #5

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

Similar topics

0
1582
by: Alistair | last post by:
Hi all, I am creating a database based site that keeps track of books, who has read them and the comments they have. After a little help in M.P.I.asp.DB I managed to create a database (access 2000) as follows USERS TABLE
0
1816
by: Neo | last post by:
Hi Everyone I am trying to set and retrieve NTFS permssions for fileshares on remote machine using ActiveDs Interop. It works for domain groups and users but when try to retrieve permssions for local groups and users it gives me dangling SIDs. While setting permssions how can I indicate whether the user or group is local or a domain group ?. Following is the code snippet I am using for retrieving permissions
7
1223
by: luna_s | last post by:
i've been playing with this code to return an ID on an insert - it seems a little dirty/hacky to me stored proc goes something like this (ive stripped out uneccesary sql code - the proc works fine) :- CREATE PROCEDURE uipersonal declare all the variables here
0
2072
by: Andy | last post by:
Hi All. I'm working for a company that has set out a guideline for retrieving data from a database. Nobody can explain to me the reason for the following. When retrieving a set of records from database to a VB.net app, they retrieve the database fields as a record set eg. "select name, suburb from myTable"
17
2697
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...
11
2030
by: Nemisis | last post by:
Hi everyone, sorry if this post gets really long, i just wanna make sure i fully explain what i am trying to do. I am new to OOP and .net 2.0, so if this is obvious, i am sorry. I have wrote a data access layer, which contists of separate servicebases for each object within my database. CompanyDataService (contains CRUD methods) ContactDataService (contains CRUD methods)
15
3533
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
35531
ADezii
by: ADezii | last post by:
One question which pops up frequently here at TheScripts is: 'How do I retrieve data from a Recordset once I've created it?' One very efficient, and not that often used approach, is the GetRows() Method of the Recordset Object. This Method varies slightly from DAO to ADO, so for purposes of this discussion, we'll be talking about DAO Recordsets. The ADO approach will be addressed in the following Tip. We'll be using a Query, consisting of 5...
3
43522
ADezii
by: ADezii | last post by:
Last Tip, we demonstrated the technique for retrieving data from a DAO Recordset, and placing it into a 2-dimensional Array using the GetRows() Method. This week, we will cover the same exact Method (GetRows()), but only as it applies to an ADO Recordset. Although there are similarities in the 2 methodologies, the ADO Method offers 2 more Optional Arguments, is a little more complex, and of course, the syntax is different in creating the...
0
8969
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8788
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
9476
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9335
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...
0
9208
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...
1
6751
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
6053
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4570
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
3279
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

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.