Microsoft SQL Server Compact版插入查询​​返回选择@@ identity

时间:2014-10-10 19:13:59

标签: c# sql return sql-server-ce-3.5

我正在尝试创建一个将记录插入Microsoft SQL Server Compact 3.5版数据库并返回新插入行的id的函数。

这是我的代码:

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;
}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

SELECT @@IDENTITY AS ID应与INSERT语句在同一查询中。

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

@@IDENTITY