Sql server 如何在实体框架中获取存储过程@错误值?

Sql server 如何在实体框架中获取存储过程@错误值?,sql-server,tsql,stored-procedures,error-handling,Sql Server,Tsql,Stored Procedures,Error Handling,我使用的是.NET3.5SP1 我有一个存储过程返回事务结果,如下所示: 我正在尝试获取返回的@错误状态代码。在EFV1中,我创建了FunctionImport“SetPrice”,并通过在“mycontext”类中创建方法调用它,如下所示: 这导致了以下错误: The data reader returned by the store data provider does not have enough columns for the query requested. at Syste

我使用的是.NET3.5SP1

我有一个存储过程返回事务结果,如下所示:



我正在尝试获取返回的@错误状态代码。在EFV1中,我创建了FunctionImport“SetPrice”,并通过在“mycontext”类中创建方法调用它,如下所示:



这导致了以下错误:

The data reader returned by the store data provider does not have enough columns for the query requested. at System.Data.EntityClient.EntityCommandDefinition.ConstantColumnMapGenerator.System.Data.EntityClient.EntityCommandDefinition.IColumnMapGenerator.CreateColumnMap(DbDataReader reader) at System.Data.EntityClient.EntityCommandDefinition.Execute(EntityCommand entityCommand, CommandBehavior behavior) at System.Data.EntityClient.EntityCommand.ExecuteReader(CommandBehavior behavior) at System.Data.EntityClient.EntityCommand.ExecuteScalar[T_Result](Func`2 resultSelector) at System.Data.EntityClient.EntityCommand.ExecuteScalar()
请告知如何解决此问题。


谢谢。

EF v1从存储过程返回标量值时出现问题。有更多信息。

答案很长,但对于SQL 2005+您不需要使用@@ERROR。对于SQL Server 2000,您需要以不同方式使用if。。。因为您使用的是存储过程,所以如果您在Windows上使用实体框架,或者在Solaris上使用JTD,那么这是不相关的

(顺便说一句,SQL是有缺陷的)

如果第一次更新失败,这可能不会捕获错误@@错误仅具有最后一条语句的值:

 UPDATE item_price_table SET price=@price   WHERE itemid=@itemId 
 UPDATE order_table SET price=@price   WHERE itemid=@itemId 
 SELECT @myERROR = @@ERROR, @myRowCount = @@ROWCOUNT
您需要在每个DDL语句后检查:

 UPDATE item_price_table SET price=@price   WHERE itemid=@itemId 
 SELECT @myERROR = @@ERROR, @myRowCount = @@ROWCOUNT
 IF @myERROR <> 0 GOTO HANDLE_ERROR

 UPDATE order_table SET price=@price   WHERE itemid=@itemId 
 SELECT @myERROR = @@ERROR, @myRowCount = @@ROWCOUNT
 IF @myERROR <> 0 GOTO HANDLE_ERROR  
或者简单地在SQLServer2005+中使用TRY/CATCH。并在catch块中显示错误

无论如何,在这两种情况下,您都不需要读取@错误或返回值。。。您依赖于捕获SQLException。对我来说,存储的proc要么返回有意义的数据,要么返回异常(任何数据都被忽略或无效)


PS:为什么不使用@ROWCOUNT来存储它?

谢谢。正如那篇文章中提到的,SELECT语句是必需的。
在返回前添加SELECT时,查询执行正确。

+1完全同意,@@ERROR在许多方面都有缺陷。谢谢。我创建了示例存储过程来探索EFV1中的SP支持。
 UPDATE item_price_table SET price=@price   WHERE itemid=@itemId 
 UPDATE order_table SET price=@price   WHERE itemid=@itemId 
 SELECT @myERROR = @@ERROR, @myRowCount = @@ROWCOUNT
 UPDATE item_price_table SET price=@price   WHERE itemid=@itemId 
 SELECT @myERROR = @@ERROR, @myRowCount = @@ROWCOUNT
 IF @myERROR <> 0 GOTO HANDLE_ERROR

 UPDATE order_table SET price=@price   WHERE itemid=@itemId 
 SELECT @myERROR = @@ERROR, @myRowCount = @@ROWCOUNT
 IF @myERROR <> 0 GOTO HANDLE_ERROR  
 ...
 HANDLE_ERROR:
     ROLLBACK TRAN1
     RAISERROR ('Oops: %i', 16, 1, @myERROR) --to pass error number if you really want