2013-06-12 58 views
1

我需要返回插入記錄的值以傳遞給打開表單的代碼。我如何得到這個價值?下面的代碼添加一條記錄並刷新一個datagridview。插入行的返回值

System.Data.SqlClient.SqlConnection sqlConnection1 = 
       new System.Data.SqlClient.SqlConnection("Data Source=***.**.***.**,****;Initial Catalog=newCityCollection_Aracor;Persist Security Info=True;User ID=4456r;Password=654935749653"); 

System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(); 
cmd.CommandType = System.Data.CommandType.Text; 
cmd.CommandText = "INSERT PropertyInformation (ClientKey) VALUES (1)"; 
cmd.Connection = sqlConnection1; 

sqlConnection1.Open(); 
cmd.ExecuteNonQuery(); 
sqlConnection1.Close(); 

this.propertyInformationDataGridView.Invalidate(); 
this.propertyInformationDataGridView.EndEdit(); 
this.propertyInformationDataGridView.Refresh(); 
this.newCityCollectionDataSet.AcceptChanges(); 
this.propertyInformationTableAdapter.Fill(newCityCollectionDataSet.PropertyInformation); 
+0

這是一個有點難以理解。我能獲得更多的上下文嗎? – phadaphunk

+1

你在說什麼「價值」? –

+0

我正在使用窗體上的Datagridview作爲案例管理工具來選擇記錄。我希望能夠添加記錄並立即打開表單。我知道如何打開表格以及什麼但不知道如何檢索新創建的記錄的PK。所以點擊按鈕,創建記錄,檢索PK,然後打開記錄在表單中是我的目的。 – korrowan

回答

4

更改您的SQL語句是這樣的:

INSERT PropertyInformation (ClientKey) VALUES (1); 
SELECT * FROM PropertyInformation WHERE RecordID = scope_identity() 

SCOPE_IDENTITY()應該給你當前會話最後插入的標識列(記錄ID),這將是該行的ID你只是插入到PropertyInformation中。

+5

更好使用scope_identity()函數,因爲@@ IDENTITY可能會被類似trigger的東西改變。 –

+0

好吧我如何將查詢中的值拉出來?例如,我會做類似System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(); cmd.CommandType = System.Data.CommandType.Text; cmd.CommandText =「INSERT PropertyInformation(ClientKey)VALUES(1)」; cmd.CommandText =「SELECT CaseNumberKey FROM PropertyInformation WHERE RecordID = @@ IDENTITY」; cmd.Connection = sqlConnection1; – korrowan

+1

@korrowan如果** CaseNumberKey **是一個簡單的值(通常是int/long),那麼可以使用ExecuteScalar()來執行插入並檢索該值。否則(或者如果您需要多個列),您需要像查詢一樣處理命令並將數據拉回到DataSet中。 – BlargleMonster

0

我建議你將這樣的操作包裝在存儲過程中。讓它返回新記錄的ID作爲OUT變種。

CREATE PROC CreateRecord(@ID INT OUT, @Value1 VARCHAR(100), @Value2 VARCHAR(100)) 
AS BEGIN 
    INSERT INTO MyTable (Field1, Field2) VALUES (@Value1, @Value2) 
    SET @ID = SCOPE_IDENTITY() 
END 

...然後你可以檢索你的SqlCommandParameters財產OUT PARAM。就我個人而言,我喜歡用一種方法來包裝它;這裏是我使用的同步執行帶參數的存儲過程,稍作簡化:

public static Dictionary<string, object> ExecSproc(string connectionString, string proc, IEnumerable<SqlParameter> parameters) 
    { 
    SqlCommand command = null; 
    try 
     { 
     SqlConnection connection = GetConnection(connectionString); 

     // Build the command 
     command    = new SqlCommand(proc, connection); 
     command.CommandTimeout = TimeOutSeconds; 
     command.CommandType = CommandType.StoredProcedure; 

     // Append parameters 
     SqlParameter retValue = new SqlParameter("Return value", null); 
     retValue.Direction = ParameterDirection.ReturnValue; 
     command.Parameters.Add(retValue); 
     if (parameters != null) 
      foreach (SqlParameter param in parameters) 
       command.Parameters.Add(param); 

     // GO GO GO! 
     command.ExecuteNonQuery(); 

     // Collect the return value and out parameters 
     var outputs = new Dictionary<string, object>(); 
     foreach (SqlParameter param in command.Parameters) 
      if (param.Direction != ParameterDirection.Input) 
       outputs.Add(param.ParameterName, param.Value); 
     return outputs; 
     } 
    finally 
     { 
     if (command != null) 
      { 
      command.Cancel(); // This saves some post-processing which we do not need (out vars and a row count) 
      command.Dispose(); 
      } 
     } 
    } 

下面是它看起來像在使用中:

var results = SQL.ExecSproc(connectionString, sprocName, "@Success OUT", false, "@InVar1", 123, "InVar2", "ABC"); 
if ((bool)results["@Success"] == false) 
    throw new ApplicationException("Failed."); 
+0

我需要一個參考來運行這個。我使用system.data,但它似乎需要別的東西。 – korrowan

+0

'System.Data.SqlClient' – zimdanen