c# - 从存储过程 "WITH RESULT SETS"读取时无法使用 CommandBehavior.KeyInfo

标签 c# .net sql-server

在 SQL Server 2012 或更高版本中运行以下命令

CREATE TABLE TestTable1
(
  Dim varchar(500),
  Measure money,
  PRIMARY KEY (Dim)
)
GO

CREATE TABLE TestTable2
(
  Dim varchar(500),
  Measure money,
  PRIMARY KEY (Dim)
)
GO

CREATE PROCEDURE [dbo].[usp_InnerSp]
(
       @Sql varchar(max)
)
AS
BEGIN
  EXEC(@sql)
END
GO

CREATE PROCEDURE [dbo].[usp_ParentSp]
AS
BEGIN
  DECLARE @sql VARCHAR(MAX);
  SET @sql = 'SELECT t1.* FROM TestTable1 t1 INNER JOIN TestTable2 t2 ON t1.Dim = t2.Dim'
  EXEC [dbo].[usp_InnerSp] @sql
  WITH RESULT SETS (
   (
    [Dim] VARCHAR(500),
    [Measure] MONEY
   )
  );
END
GO

在 C# 中创建控制台应用程序

static void Main(string[] args)
{
    using (SqlConnection connection = new SqlConnection(@"Data Source=.\SQL2014;Initial Catalog=AdventureWorksDW2012;Integrated Security=SSPI;"))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand("usp_ParentSp", connection))
        {
            command.CommandType = CommandType.StoredProcedure;
            using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo))
            {
            }
        }
    }
}

运行代码时,会出现以下 System.Data.SqlClient.SqlException 异常:

EXECUTE statement failed because its WITH RESULT SETS clause specified 2 column(s) for result set number 1, but the statement sent 3 column(s) at run time.

我希望 .Net 运行存储过程,即使它出于某种原因无法检测到主键也是如此。

问题:你会推荐什么?这是 .Net 或 SQL Server 中的错误?

最佳答案

为什么在已经选择 [Dim] 列 (t1.*) 时还要使用 CommandBehavior.KeyInfo

要么根本不使用 CommandBehavior.KeyInfo(最佳方法)。

或者改变

WITH RESULT SETS (([Dim] VARCHAR(500), [Measure] MONEY));

WITH RESULT SETS (([Dim] VARCHAR(500), [Measure] MONEY, [PrimaryKey] VARCHAR(500)));

(最坏的解决方案)。

或者将t1.*改为t1.Measure

WITH RESULT SETS (([Dim] VARCHAR(500), [Measure] MONEY));

WITH RESULT SETS (([Measure] MONEY, [PrimaryKey] VARCHAR(500)));

(好于 2 但仍差于 1)。

关于c# - 从存储过程 "WITH RESULT SETS"读取时无法使用 CommandBehavior.KeyInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28861418/

相关文章:

c# - Linq "Unable to cast object of type ' System.DateTime' 键入 'System.String'“错误

c# - 验证影响整个表单,不能按下任何按钮

c# - 在多个线程上运行 Parallel.Foreach 的性能

sql-server - 在表中使用 VARCHAR(MAX) 有缺点吗?

SQL Server - 从表变量中删除不是即时的?

c# - P/Invoke CryptUnprotectData 中断 SqlConnection 构造函数

c# - 将项目添加到通用列表时出现问题

c# - 从 Razor 页面上传到 Azure 文件共享

c# - 基于计数的 orderby 相关性的 LINQ 关键字搜索 (LINQ to SQL)

php - SQL Server : Given a year find everything (inclusive) from the year previous and given year