简体   繁体   English

C#SQL,获取受UPDATE影响的行

[英]C# SQL, Get rows affected by UPDATE

Essentially, what I am wondering if possible is how to retrieve the data from newly updated rows after executing a stored procedure. 本质上,我想知道是否可能是在执行存储过程之后如何从新更新的行中检索数据。

For instance, say we have a simple SQL stored procedure 例如,假设我们有一个简单的SQL存储过程

sp_PROCS_UPDATE_UpdateUserName:

    UPDATE users SET Name = "David";

From that, I want to be able to retrieve the actual records which names were updated, not just the count. 由此,我希望能够检索更新了名称的实际记录,而不仅仅是计数。

Is this even possible with C# ? 使用C#甚至可能吗?

假设您正在使用SQL Server,请尝试以下操作:

UPDATE users SET Name = "David" output inserted.*;

Here is a code snippet using System.Data.SqlClient namespace, you may also need to using System.Data as well. 这是使用System.Data.SqlClient命名空间的代码段,您可能还需要using System.Data

This code sample will execute the query and return the affected rows. 此代码示例将执行查询并返回受影响的行。

var affectedRows = -1;
var cs = ""; // your connection string
try 
{
    var cn = new SqlConnection(cs);
    cn.Open();
    using (var cmd = cn.CreateCommand())
    {
        cmd.CommandText = your_query; // TBD;
        var prm = new SqlParameter("prm", value); // as needed
        cmd.Parameters.Add(prm); // as needed
        affectedRows = cmd.ExecuteNonQuery();
    }
    /// and if you have nothing else to do.
    cn.Close();
    cn.Dispose();
    cn = null;

}
catch(Exception ex)
{
    System.Diagnostics.Trace.TraceError("Whoops! {0}", ex);
    // error handling
}

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我的C#代码没有更新SQL Server数据库,尽管我得到了正确的受影响行数 - Why doesn't my C# code update the SQL Server database although I get the correct number of affected rows 当我单击更新按钮以更新SQL C#中的数据库值时,所有行都受到相同值的影响 - When i click the update button to update database values in SQL C# All Rows Are Affected by the same value 如果在 c# 中运行 sql 脚本时遇到 sql 异常,如何获取受影响的行数 - How to get the number of rows affected, if it hits sql exception while running the sql script in c# ExecuteNonQuery()不会在C#和SQL Server数据库中返回受影响的行 - ExecuteNonQuery() does not return the affected rows in C# and SQL Server database SQL / C#获取受插入影响的行的ID - SQL/C# Get ID of the row affected by Insert SQL更新命令不起作用,受影响的行返回0 - SQL update command not working, rows affected returns 0 获取SQL表的受影响行数 - Get Count of Affected rows of SQL table C#,SQL更新多行 - C# , SQL update multiple rows 如何在SQL Server或ASP.NET C中强制执行特定数量或范围的受影响的行# - How to enforce a certain number or range of affected rows in SQL Server or ASP.NET C# C#-SQL查询返回受影响的项目 - C# - SQL query returning items affected
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM