how to get the ID of the record that is update in C#

时间:2016-04-25 09:19:28

标签: c# sql asp.net sql-server

I am able to get a sql query that can return the ID of a record that is update in the Database; that ID is needed to update other records.

public int updateCases(int id,string fname)
{
 string query="update bio_data set firstName=@fname OUTPUT INSERTED.ID where id=@ID";
    int IDValue = 0;
    try
    {
        con.Open();
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.Parameters.AddWithValue("@ID",id);
        cmd.Parameters.AddWithValue("@fname",fname);

        IDValue = Convert.ToInt32(cmd.ExecuteNonQuery());  // this is incorrect because it always return one
        if (IDValue <= 0)
        {
            return 0;
        }
        return IDValue; 
    }
    catch (Exception ex)
    {
        error.Text = "An Error Occur while update a case Bio_data!!" + ex.Message;
        error.ForeColor = Color.Red;
        return 0;
    }
    finally
    {
        con.Close();
    }

but I don't know how to get that updated ID value in C# Can someone please help me; thanks in advanced!!

1 个答案:

答案 0 :(得分:2)

认为您真的在问如何检索INSERTUPDATE返回的带有OUTPUT子句的结果集。您使用ExecuteReader代替ExecuteNonQuery

以下是简化示例:

创建测试表

SELECT * INTO Test FROM (VALUES (1, 'ABC'),(2,'DEF'),(3,'ABC')) A(Id, Val)

C#代码

更新Val 'ABC'返回更新行的位置并打印它们(原谅可疑错误处理等)

var conString = ...;
var query = "UPDATE TEST SET Val ='XYZ' OUTPUT INSERTED.* WHERE Val = @Val";

using (SqlConnection con = new SqlConnection(conString))
{

    con.Open();
    using (SqlCommand cmd = new SqlCommand(query, con))
    {
        cmd.Parameters.AddWithValue("@Val", "ABC");

        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                Console.WriteLine(reader["id"] + " " + reader["Val"]);
            }
        }
    }

打印

1 XYZ
3 XYZ

SELECT * FROM Test现在显示

Id          Val
----------- ----
1           XYZ
2           DEF
3           XYZ

希望这会有所帮助。您应该知道这种方法可能会出现触发器问题以及SQL错误的引发/处理问题。

相关问题