我想使用 C# ADO.Net 接收此插入命令的所有输出主键。
我在 SQL Server 2012 Studio 中运行它,我看到了包含所有值的结果表,那么是否可以从 C# 获取该表?
INSERT INTO dbo.Suspension
(pallet_position, processing_pallet_pkey, datetime_created, datetime_updated,
created_by, updated_by)
OUTPUT INSERTED.pkey VALUES
(1, 2, '20141013 16:27:25.000', '20141013 16:27:25.000', 2, 2),
(2, 2, '20141013 16:27:25.000', '20141013 16:27:25.000', 2, 2),
(3, 2, '20141013 16:27:25.000', '20141013 16:27:25.000', 2, 2),
(4, 2, '20141013 16:27:25.000', '20141013 16:27:25.000', 2, 2);
我在 C# ADO.NET 中尝试过的内容。但 DataTable 没有从 insertedOutput
获取任何值。
SqlCommand cmd = new SqlCommand(insertQuery, this.conn);
var insertedOutput = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(insertedOutput); // something wrong here
注意到我从调试器复制了 SQL 代码。效果很好。 (不确定“this.”来自哪里,但它没有引起任何问题)
在调试器中,insertedOutput 中有 cmd.ExecuteReader() 的结果,但我无法从 dt (DataTable 变量)复制这些结果。
最佳答案
您的查询看起来不错(除了 this.created_by
/this.updated_by
,这让我感到困惑,但是......如果你说它有效...... )
因此,我最初的想法是:您是否可能有一个替换触发器,错误地只处理一行?尽管我希望报告:
The target table 'dbo.Suspension' of the DML statement cannot have any enabled triggers if the statement contains an OUTPUT clause without INTO clause.
以下 3 种读取该 sql(或与其非常相似的版本)的方法都可以正常工作:
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
const string insertQuery = @"
INSERT INTO dbo.Suspension
(pallet_position, processing_pallet_pkey, datetime_created, datetime_updated,
[this.created_by], [this.updated_by])
OUTPUT INSERTED.pkey VALUES
(1, 2, '20141013 16:27:25.000', '20141013 16:27:25.000', 2, 2),
(2, 2, '20141013 16:27:25.000', '20141013 16:27:25.000', 2, 2),
(3, 2, '20141013 16:27:25.000', '20141013 16:27:25.000', 2, 2),
(4, 2, '20141013 16:27:25.000', '20141013 16:27:25.000', 2, 2);";
// via datatable
DataTable dt = new DataTable();
using (SqlCommand cmd = new SqlCommand(insertQuery, conn))
using (var insertedOutput = cmd.ExecuteReader())
{
dt.Load(insertedOutput);
}
Console.WriteLine(dt.Rows.Count); // 4
// via manual read
var list = new List<int>();
using (SqlCommand cmd = new SqlCommand(insertQuery, conn))
using (var insertedOutput = cmd.ExecuteReader())
{
while(insertedOutput.Read())
{
list.Add(insertedOutput.GetInt32(0));
}
}
Console.WriteLine(list.Count); // 4
// via dapper
var ids = conn.Query<int>(insertQuery).ToList();
Console.WriteLine(ids.Count); // 4
}
关于c# - 如何使用 C# ADO.Net 从 SQL Server 插入命令获取多行输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26337162/