|
web
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
How do I get back a newly created Primary keysql server 2000 database table. How do I obtain the value of primary key - field name PK - for the newly created record. The field PK is an identity field that automatically increments its value. Dim MyConn As New SqlClient.SqlConnection MyConn.ConnectionString = g_SQLConnStr Dim Mycommand As New SqlClient.SqlCommand Try Dim NewRecordPK As Integer Mycommand.CommandText = "Insert into MyTable (Data1,Data2) " & _ "VALUES ('Data1Value','Data2Value') Mycommand.Connection = MyConn MyConn.Open() NewRecordPK = Mycommand.ExecuteScalar() etc.... I thought that ExecuteScalar would return the value of the first field of the affected record but it always returns 0, yet I can see in the table that the record has been added OK with a PK value other than 0, ie it increments correctly. Any help would be greatly appreciated, Bob Try to add at your SQL query, a Return @@IDENTITY ...
-- Show quoteHide quoteTiago Salgado // http://weblogs.pontonetpt.com/tiagosalgado On Sat, 21 Oct 2006 20:39:42 +0100, rdufour <bduf***@sgiims.com> wrote: > ted, If you are using SQL Server 2005, you can include the OUTPUT clause in your
SQL statement. Assuming that the name of your primary key field is PK, use this statement. INSERT INTO MyTable (Data1,Data2) OUTPUT INSERTED.PK VALUES ('Data1Value','Data2Value') ----- Tim Patrick Start-to-Finish Visual Basic 2005 Thanks to both of you.
Bob Show quoteHide quote "rdufour" <bduf***@sgiims.com> wrote in message news:unA6MjU9GHA.568@TK2MSFTNGP05.phx.gbl... > Using Vs2005. In this snippet of code I would be creating a new record in > a sql server 2000 database table. How do I obtain the value of primary > key - field name PK - for the newly created record. The field PK is an > identity field that automatically increments its value. > > Dim MyConn As New SqlClient.SqlConnection > MyConn.ConnectionString = g_SQLConnStr > Dim Mycommand As New SqlClient.SqlCommand > Try > Dim NewRecordPK As Integer > Mycommand.CommandText = "Insert into MyTable (Data1,Data2) " & > _ > "VALUES ('Data1Value','Data2Value') > Mycommand.Connection = MyConn > MyConn.Open() > NewRecordPK = Mycommand.ExecuteScalar() > > etc.... > > I thought that ExecuteScalar would return the value of the first field of > the affected record but it always returns 0, yet I can see in the table > that the record has been added OK with a PK value other than 0, ie it > increments correctly. > > Any help would be greatly appreciated, > Bob >
Backing up with SQL MO
Best way to store dataset to disk??? Query results to file Transparent BackGround Newb looking for data binding help Datasets and Adapter Updates Webbrowser control - buffering - audio/video playback problem... validate radio button in groupbox What is the event to trap when user clicks X to close form? Using VB and ADO.NET |
|||||||||||||||||||||||