Tuesday, February 21, 2012

SCOPE_IDENTITY plzzzzz help me

this is my code, i really want a basic easy way without using procedures to do a simple task to response.write(last record added) using scope_identity...
asp.net/VB
===================================================================================
Sub click_addnew(sender as object, e as system.eventargs)

Dim oDR as System.Data.SQLClient.SQLDataReader
Dim oCom As System.Data.SQLClient.SqlCommand
Dim oConn as System.Data.SQLClient.SQLConnection
Dim recnumber as integer
try
oConn = New System.Data.SQLClient.SQLConnection ("server=xxx.xxx.xx; initial catalog=xxx;uid=xxx;pwd=xxx")
oConn.Open()
oCom = New System.Data.SQLClient.SqlCommand()
oCom.Connection = oConn

oCom.CommandText = "INSERT INTO hooliganproducts (hooligantitle, hooliganprice, hooligandescription, hooliganpartno, hooligancata) VALUES ('test' , '100' , 'test' , 'test' , 'test') select scope_identity"
oDR = oCom.ExecuteReader()
response.Write(oDR) 'THIS IS WHERE I WANT TO DISPLAY THE NUMBER OF THE LAST RECORD

catch
Response.Write("Error:" & err.Description)
Finally
oDR = Nothing
oCom = Nothing
oConn.Close()
oConn = Nothing
end try

End Sub
=============================================================================

Please can someone help, feel like i have been banging my head up a brick wall all day, have spent the whole day trying to find an answer.
Thank you in advance
Darren

Multiple SQL commands in a batch should be separated by semicolons (;). Try putting a semicolon between theINSERT statement and theselect scope_identity statement.
|||(1) You need brackets after SCOPE_IDENTITY as in SCOPE_IDENTITY().
(2) You might want to use ExecuteScalar since you are only getting backone value. So you can also avoid the overhead of creating a datareader.
So your code would look something like :
oConn = New System.Data.SQLClient.SQLConnection ("server=xxx.xxx.xx; initial catalog=xxx;uid=xxx;pwd=xxx")
'oConn.Open() - OPEN ONLY WHEN YOU NEED AND CLOSE IMMEDIATELY.
oCom = New System.Data.SQLClient.SqlCommand()
oCom.Connection = oConn
oCom.CommandText= "INSERT INTO hooliganproducts (hooligantitle, hooliganprice,hooligandescription, hooliganpartno, hooligancata) VALUES ('test' ,'100' , 'test' , 'test' , 'test') select SCOPE_IDENTITY()"
Dim newId as Integer
try
oConn.Open()
newId = oCom.ExecuteScalar()
response.Write(newId) 'THIS IS WHERE I WANT TO DISPLAY THE NUMBER OF THE LAST RECORD

catch
Response.Write("Error:" & err.Description)
Finally
oCom = Nothing
oConn.Close()
oConn = Nothing
end try
|||Thank you both. feel much better now, got it working.

No comments:

Post a Comment