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); 
4

2 回答 2

4

将您的 SQL 更改为:

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

scope_identity() 应该为您提供当前会话的最后插入的标识列(记录 ID),这将是您刚刚插入 PropertyInformation 的行的 ID。

于 2013-06-12T18:25:04.387 回答
0

我建议您将这样的操作包装在存储过程中。让它以OUTvar 形式返回新记录的 ID。

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

...然后您可以检索 OUT 属性中的SqlCommand参数Parameters。就个人而言,我喜欢将其包含在一个方法中;这是我用于同步执行带参数的存储过程的方法,稍微简化:

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.");
于 2013-06-12T19:00:05.247 回答