简体   繁体   中英

Microsoft SQL Server Compact edition insert query return select @@identity

I am trying to create a function which inserts a record into a Microsoft SQL Server Compact edition 3.5 database and returns the id of the newly inserted row.

Here's my code:

upit = "insert into Crtez (Ncrteza, ProjID, lilu, lide, dubinaRova, d1, d2, ZCdulina, ZCpromjer, dBusenja) 
        values ('primjer 2 rolaza.dwg', 3, 49192.62, 49222.62, 3.11, 74.7693403335958, 15.2495262383346, 14,0,0.00)";

public static int UpisiUBazu(String putanja, String upitUpisa)
{
    int id = default(int);
    SqlCeConnection con = new SqlCeConnection();

    try
    {
        String constring = "Data Source=" + putanja;

        using (con = new SqlCeConnection(constring))
        {
            con.Open();
            SqlCeTransaction tr = con.BeginTransaction();
            SqlCeCommand com = null;
            com = new SqlCeCommand(upitUpisa, con);
            com.Transaction = tr;
            com.ExecuteNonQuery();
            com = new SqlCeCommand(@"SELECT @@IDENTITY AS ID", con);
            object o = com.ExecuteScalar();
            id = Convert.ToInt32(o);
        }
    }
    catch (SqlCeException ex)
    {
        MessageBox.Show("Pojavila se greška: " + ex.Message + "/" + ex.NativeError + "/" + ex.InnerException);
    }
    finally
    {
        con.Close();
    }
    return id;
}

What am I doing wrong??

SELECT @@IDENTITY AS ID should be in same query with INSERT statement.

INSERT INTO Crtez (...) VALUES (...); SELECT @@IDENTITY AS ID

@@IDENTITY

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM