Solved

executeScalar always returns 0 - trying to get ID of record just inserted

Posted on 2012-03-21
6
279 Views
Last Modified: 2012-04-19
For some reasons the excutescalar result is always 0 (trying to get ID of record inserted)
i've read about input/output parameters but all the stuff i read is to do with SP's and not inline sql like this:

     Public Function insertGroupLoan(ByVal _groupId As Integer, _
                             ByVal _loanId As Integer, _
                             ByVal _LoanActive As Integer, _
                             ByVal _notes As String) As Integer

        Dim dataHelperInsert As New HelperInsert

        'construct SQL Statement
        Dim sb As New StringBuilder
        sb.Append("INSERT INTO   GroupLoans ")
        sb.Append("(FK_GroupId, FK_LoanId, LoanActive, Notes)")
        sb.Append(" VALUES (")
        sb.Append("@FK_GroupId")
        sb.Append(",")
        sb.Append("@FK_LoanId")
        sb.Append(",")
        sb.Append("@LoanActive")
        sb.Append(",")
        sb.Append("@Notes")
        sb.Append(")")

        Dim IdOfRow As Integer
        Dim conn = New SqlCeConnection(My.Settings.mfmConn)
        Dim cmd As New SqlCeCommand
        cmd.Connection = conn

        cmd.CommandText = sb.ToString
        cmd.Parameters.Add("@FK_GroupId", SqlDbType.Int).Value = _groupId
        cmd.Parameters.Add("@FK_LoanId", SqlDbType.Int).Value = _loanId
        cmd.Parameters.Add("@LoanActive", SqlDbType.Bit).Value = CBool(_LoanActive)
        cmd.Parameters.Add("@Notes", SqlDbType.NVarChar).Value = _notes

        conn.Open()
        IdOfRow = CInt(cmd.ExecuteScalar())
        conn.Close()

        Return IdOfRow
  
    End Function

Open in new window

0
Comment
Question by:websss
6 Comments
 
LVL 6

Expert Comment

by:kswathi
ID: 37745995
After the insert statement use the below sql to retriecve the identity column.
     Public Function insertGroupLoan(ByVal _groupId As Integer, _
                             ByVal _loanId As Integer, _
                             ByVal _LoanActive As Integer, _
                             ByVal _notes As String) As Integer

        Dim dataHelperInsert As New HelperInsert

        'construct SQL Statement
        Dim sb As New StringBuilder
        sb.Append("INSERT INTO   GroupLoans ")
        sb.Append("(FK_GroupId, FK_LoanId, LoanActive, Notes)")
        sb.Append(" VALUES (")
        sb.Append("@FK_GroupId")
        sb.Append(",")
        sb.Append("@FK_LoanId")
        sb.Append(",")
        sb.Append("@LoanActive")
        sb.Append(",")
        sb.Append("@Notes")
        sb.Append(")")

    [b]    sb.Append("SELECT SCOPE_IDENTITY()")[/b]

        Dim IdOfRow As Integer
        Dim conn = New SqlCeConnection(My.Settings.mfmConn)
        Dim cmd As New SqlCeCommand
        cmd.Connection = conn

        cmd.CommandText = sb.ToString
        cmd.Parameters.Add("@FK_GroupId", SqlDbType.Int).Value = _groupId
        cmd.Parameters.Add("@FK_LoanId", SqlDbType.Int).Value = _loanId
        cmd.Parameters.Add("@LoanActive", SqlDbType.Bit).Value = CBool(_LoanActive)
        cmd.Parameters.Add("@Notes", SqlDbType.NVarChar).Value = _notes

        conn.Open()
        IdOfRow = CInt(cmd.ExecuteScalar())
        conn.Close()

        Return IdOfRow
  
    End Function

Open in new window

alternatively you can check the below link

http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/91bd10ce-c83b-4766-920b-2137ddc29908

or

http://stackoverflow.com/questions/5228780/how-to-get-last-inserted-id
0
 
LVL 53

Expert Comment

by:Dhaest
ID: 37745999
0
 

Author Comment

by:websss
ID: 37746202
Thanks

I've tried to use this example but it errors on this line
ID = CInt(cmd.ExecuteScalar())

Open in new window


with the following:
---------------------------
There was an error inserting the member
---------------------------
There was an error parsing the query. [ Token line number = 1,Token line offset = 374,Token in error = Select ]
---------------------------
OK  
---------------------------


Here is the code

    Public Function insertMember(ByVal _memberName As String, _
                                ByVal _gender As String, _
                                ByVal _phoneNumber As String, _
                                ByVal _noOfDependants As Integer, _
                                ByVal _maritalStatus As String, _
                                ByVal _businessType As String, _
                                ByVal _rent As String, _
                                ByVal _prevEmployment As String, _
                                ByVal _otherNotes As String, _
                                ByVal _mpesaEnabled As Boolean, _
                                ByVal _centreId As Integer, _
                                ByVal _nationalId As String) As Integer

    
        'construct SQL Statement
        Dim sb As New StringBuilder
        sb.Append("INSERT INTO   Members ")
        sb.Append("(MemberName, Gender, PhoneNumber, NumberOfDependants, MaritalStatus, BusinessType, Rent, PreviousEmployment, OtherNotes, MpesaEnabled, CentreId, Active, NationalIdNumber)")
        sb.Append(" VALUES (")
        sb.Append("@MemberName")
        sb.Append(",")
        sb.Append("@Gender")
        sb.Append(",")
        sb.Append("@PhoneNumber")
        sb.Append(",")
        sb.Append("@NumberOfDependants")
        sb.Append(",")
        sb.Append("@MaritalStatus")
        sb.Append(",")
        sb.Append("@BusinessType")
        sb.Append(",")
        sb.Append("@Rent")
        sb.Append(",")
        sb.Append("@PreviousEmployment")
        sb.Append(",")
        sb.Append("@OtherNotes")
        sb.Append(",")
        sb.Append("@MpesaEnabled")
        sb.Append(",")
        sb.Append("@CentreId")
        sb.Append(",")
        sb.Append("@Active")
        sb.Append(",")
        sb.Append("@NationalIdNumber")
        sb.Append("); Select Scope_Identity()")


        Dim ID As Integer = 0

        Using conn As New SqlCeConnection(My.Settings.mfmConn)
            Using cmd As New SqlCeCommand(sb.ToString, conn)
                cmd.Parameters.Add("@MemberName", SqlDbType.NVarChar).Value = _memberName
                cmd.Parameters.Add("@Gender", SqlDbType.NVarChar).Value = _gender
                cmd.Parameters.Add("@PhoneNumber", SqlDbType.NVarChar).Value = _phoneNumber
                cmd.Parameters.Add("@NumberOfDependants", SqlDbType.Int).Value = _noOfDependants
                cmd.Parameters.Add("@MaritalStatus", SqlDbType.NVarChar).Value = _maritalStatus
                cmd.Parameters.Add("@BusinessType", SqlDbType.NVarChar).Value = _businessType
                cmd.Parameters.Add("@Rent", SqlDbType.NVarChar).Value = _rent
                cmd.Parameters.Add("@PreviousEmployment", SqlDbType.NVarChar).Value = _prevEmployment
                cmd.Parameters.Add("@OtherNotes", SqlDbType.NVarChar).Value = _otherNotes
                cmd.Parameters.Add("@MpesaEnabled", SqlDbType.Bit).Value = _mpesaEnabled
                cmd.Parameters.Add("@CentreId", SqlDbType.Int).Value = _centreId
                cmd.Parameters.Add("@Active", SqlDbType.Bit).Value = 1
                cmd.Parameters.Add("@NationalIdNumber", SqlDbType.NVarChar).Value = _nationalId
                conn.Open()
                ID = CInt(cmd.ExecuteScalar())
                conn.Close()
            End Using
        End Using

        Return ID

Open in new window


the SQL looks like this (sb.ToString)
INSERT INTO   Members (MemberName, Gender, PhoneNumber, NumberOfDependants, MaritalStatus, BusinessType, Rent, PreviousEmployment, OtherNotes, MpesaEnabled, CentreId, Active, NationalIdNumber) VALUES (@MemberName,@Gender,@PhoneNumber,@NumberOfDependants,@MaritalStatus,@BusinessType,@Rent,@PreviousEmployment,@OtherNotes,@MpesaEnabled,@CentreId,@Active,@NationalIdNumber); Select Scope_Identity()

Open in new window


any ideas?
0
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 

Author Comment

by:websss
ID: 37746219
Because of this issue with SQL CE
http://www.vbforums.com/showthread.php?t=465158

What should i do?
0
 
LVL 83

Accepted Solution

by:
CodeCruiser earned 250 total points
ID: 37765296
Do a executenonquery first with the insert statement and then do a executescalar with the select scope_identity() command.
0
 
LVL 27

Assisted Solution

by:Ark
Ark earned 250 total points
ID: 37770602
Just one more option:
SELECT MAX(" & idField & ") FROM [" & tableName & "]"
0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Help with solving error related to resources file 4 45
VB.NET 1 21
Footer for each row on Gridview 2 19
VB.Net - Get ColumnNames of SQL Table 4 10
If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

815 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now