[英]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.