2010-09-29 46 views
0

使用SqlDataSource的Im sds = new SqlDataSource();在代碼後面並使用sds.Insert()插入;請告訴我如何獲取插入的記錄主鍵值? 請注意我不使用存儲過程。sqldatasource插入返回標識值

回答

1

...:

tring sqlIns = "INSERT INTO table (name, information, other) VALUES (@name, @information, @other)"; 
db.Open(); 
try 
{ 
SqlCommand cmdIns = new SqlCommand(sqlIns, db.Connection); 
cmdIns.Parameters.Add("@name", info); 
cmdIns.Parameters.Add("@information", info1); 
cmdIns.Parameters.Add("@other", info2); 
cmdIns.ExecuteNonQuery(); 

cmdIns.Parameters.Clear(); 
cmdIns.CommandText = "SELECT @@IDENTITY"; 


// Get the last inserted id. 

int insertID = Convert.ToInt32(cmdIns.ExecuteScalar()); 


cmdIns.Dispose(); 
cmdIns = null; 
} 
catch(Exception ex) 
{ 
throw new Exception(ex.ToString(), ex); 
} 
finally 
{ 
db.Close(); 
} 

,我發現這個MSDN上

關於Michael Eakins的回答(參見上文),使用SCOPE_IDENTITY()而不是@@IDENTITY會更安全。

每MSDN SCOPE_IDENTITY

「...... SCOPE_IDENTITY只返回當前 範圍內插入的值; @@ IDENTITY不限於一個特定的範圍之內。」