2014-10-10 110 views
0

我正在試圖創建一個函數,該記錄插入Microsoft SQL Server精簡版3.5數據庫並返回新插入的行的ID。Microsoft SQL Server精簡版插入查詢​​返回select @@ identity

這裏是我的代碼:

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

我在做什麼錯?

+0

可以格式化此所以它更具可讀性?還檢查我的答案[這裏](http://stackoverflow.com/questions/25937973/sql-output-inserted/25938038#25938038)類似的問題。 – alykins 2014-10-10 19:17:00

回答

0

SELECT @@IDENTITY AS ID應與INSERT語句在同一查詢中。

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

@@IDENTITY

+0

從我讀過的內容來看,這不是最好的辦法。設置到最後插入的身份我認爲是更安全的。是|否? – alykins 2014-10-10 19:26:12

+0

@@ IDENTITY在所有範圍內返回當前會話中任何表生成的最後一個標識值。如果你不一起執行,「SELECT @@ IDENTITY AS ID」沒有意義。它在哪裏說它不是最好的方式?你能發佈鏈接嗎? – Win 2014-10-10 19:30:45

+2

http://www.sqlbadpractices.com/how-not-to-retrieve-identity-value/ – LittleBobbyTables 2014-10-10 19:35:40