Wednesday, March 21, 2012

Problem with @@identity return in stored procedure insert.

I'm having a problem I do an insert into a table but I want to return the value of the identity field of that insert so I can email a confirmation. For some reason this code doesn't work.
Below is the stored procedure I'm calling and below that the code I'm using. What am I doing wrong. The value I have returned is null when it should be a number. Any suggestions. Why does finalMagicNum2 come back null when it should grab the identity field of the inserted record.

CREATE PROCEDURE addMagicRecTest
(
@.theSequence int,
@.theSubject int,
@.theFirstName nvarchar(50)=null
@.theLastName nvarchar(75)=null
)

AS

INSERT INTO employees([Sequence],subject,firstname,lastname)
VALUES(@.theSequence,@.theSubject,@.theFirstName,@.theLastName)
SELECT @.@.identity AS finalNum

magicDataConnect = ConfigurationSettings.AppSettings("myDataConnect")
Response.Write(magicDataConnect)
magicCommand = New SqlDataAdapter("addMagicRecTest", magicDataConnect)
magicCommand.ConnectionType = CommandType.StoredProcedure
magicCommand.SelectCommand.CommandType = CommandType.StoredProcedure

' Sequence ID for request
magicCommand.SelectCommand.Parameters.Add(New SqlParameter("@.theSequence", SqlDbType.NVarChar, 8))
magicCommand.SelectCommand.Parameters("@.theSequence").Value = "41833"

' Subject for new Wac Ticket
magicCommand.SelectCommand.Parameters.Add(New SqlParameter("@.theSubject", SqlDbType.NVarChar, 8))
magicCommand.SelectCommand.Parameters("@.theSubject").Value = "1064"

' First Name Field
magicCommand.SelectCommand.Parameters.Add(New SqlParameter("@.theFirstName", SqlDbType.NVarChar, 50))
magicCommand.SelectCommand.Parameters("@.theFirstName").Value = orderFirstName

' Last Name Field
magicCommand.SelectCommand.Parameters.Add(New SqlParameter("@.theLastName", SqlDbType.NVarChar, 75))
magicCommand.SelectCommand.Parameters("@.theLastName").Value = orderLastName

DSMagic = new DataSet()
magicCommand.Fill(DSMagic,"employees")

If DSMagic.Tables("_smdba_._telmaste_").Rows.Count > 0 Then
finalMagicNum2 = DSMagic.Tables("_smdba_._telmaste_").Rows(0)("finalMagic").toString
End If

I need finalMagicNum2I usually just have the stored proc return the @.@.identity like so:


CREATE PROCEDURE addMagicRecTest

(

@.theSequence int,

@.theSubject int,

@.theFirstName nvarchar(50)=null

@.theLastName nvarchar(75)=null

)

AS

INSERT INTO employees([Sequence],subject,firstname,lastname)

VALUES(@.theSequence,@.theSubject,@.theFirstName,@.theLastName)

Return @.@.Identity

Your stored proc is not returning finalnum and your code has no output param set up in it.

Sam|||Try this code in .NET


DSMagic = new DataSet()

magicCommand.Fill(DSMagic,"employees")

If DSMagic.Tables(0).Rows.Count > 0 Then

finalMagicNum2 = DSMagic.Tables(0).Rows(0).item("finalnum").toString
'OR
'finalMagicNum2 = DSMagic.Tables(0).Rows(0).item(0).toString

End If

Hope this help

No comments:

Post a Comment