2013-06-12 61 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