插入行的返回值

时间:2013-06-12 18:17:33

标签: c# sql-server winforms

我需要返回插入记录的值以传递给代码以打开表单。我如何获得这个价值?下面的代码添加记录并刷新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); 

2 个答案:

答案 0 :(得分:4)

将SQL更改为:

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

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

答案 1 :(得分:0)

我建议你在sproc中包装这样的操作。让它将新记录的ID作为OUT var。

返回
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

...然后,您可以在SqlCommand的{​​{1}}媒体资源中检索OUT参数。就个人而言,我喜欢把它包裹在一个方法中;这是我用于同步执行带参数的sproc的内容,略有简化:

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();
            }
        }
    }
相关问题