Tuesday, February 21, 2012

returning key value with Insert

I'm using SQL-MSDE and have a table defined with a 'identity seed' column that automatically gets assigned when a record is added (I do not load this value). This column is also my KEY to this table. I'm using INSERT to add a record. Is there a way to return this KEY value after doing the INSERT?
Hello,
Use SCOPE_IDENTITY() or @.@.IDENTITY
e.g
SELECT @.@.IDENTITY
HTH
regards
|||

Thanks. Sorry, I still don't understand (fairly new to ASP.net). Code is below. After my 'ExecuteNonQuery' command is performed, I want to know the value of the IdentityColumn (not referenced in code below) that was automatically added. ?? Thanks for your patience.
******************************************************************************************


PublicSharedFunction AddReport(ByVal passRepLayoutAs Report)AsBoolean

Dim dbConnectionAs SqlConnection = QuoteDBConnection()

Dim sAddAsString = "Insert Into Report(QuoteNumber, Driver, ReportType, ReportID, OrderDate, DataFile) " _

& "Values(@.QuoteNumber, @.Driver, @.ReportType, @.ReportID, @.OrderDate, @.DataFile)"

Dim dbCmdAsNew SqlCommand(sAdd, dbConnection)

With passRepLayout

dbCmd.Parameters.Add("@.QuoteNumber", .QuoteNumber)

dbCmd.Parameters.Add("@.Driver", .Driver)

dbCmd.Parameters.Add("@.ReportType", .ReportType)

dbCmd.Parameters.Add("@.ReportID", .ReportID)

dbCmd.Parameters.Add("@.OrderDate", .OrderDate)

dbCmd.Parameters.Add("@.DataFile", .DataFile)

EndWith

dbConnection.Open()

Try

dbCmd.ExecuteNonQuery()

IdentityColumnValue = ?

AddReport =True

Catch exAs Exception

AddReport =False

EndTry

dbConnection.Close()

EndFunction

|||

Dim sAddAsString="Insert Into Report(QuoteNumber, Driver, ReportType, ReportID, OrderDate, DataFile) " _

&"Values(@.QuoteNumber, @.Driver, @.ReportType, @.ReportID, @.OrderDate, @.DataFile) SELECT SCOPE_IDENTITY()"

and use ExecuteScalar instead of ExecuteNonQuery.
dim resultidasinteger

resultid= dbCmd.ExecuteScalar()

|||Thank- you very much.

No comments:

Post a Comment