c#/ sql中的错误处理程序 [英] error handler in c#/sql

查看:118
本文介绍了c#/ sql中的错误处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的存储过程有如下错误处理:

  BEGIN  TRY 
- sql UPDATE ...
END TRY
BEGIN CATCH
声明 @ msg nvarchar 200
SET @ msg =(' 数据填充期间出错...'

SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_MESSAGE() AS ErrorMessage
@ msg ;
END CATCH





问题:

从C#代码中,我执行SP。

如果更新查询中有错误,那么C#代码似乎不是来自SP的error_mesage。

那么,我应该使用raiserror或类似的东西而不是开始捕获部分中的select吗?

谢谢

解决方案

在Catch部分使用SqlException来获取Sql错误。

 尝试 
{
// 在此致电您的SP
}
catch (SqlException ex)
{
lblEreMsg.Text = ex.Message;
}
< pre> < / pre >


是的,实际上您处理了存储过程中的异常。所以你没有从.NET应用程序中获得异常。是的,你是对的。如果您的应用程序需要知道异常,那么您可以使用raiseerror函数。

提高错误详情



您也可以使用throw语句。 tsql throw 示例



< pre lang =SQL> 声明 @ i int < /跨度>;
开始尝试
设置 @我 = ' a';
end 尝试
开始 catch
print ' 错误:' + error_message();
throw;
end catch


Hi,
My stored procedures have error handling as follows:

BEGIN TRY
--sql UPDATE...
END TRY
BEGIN CATCH 
	declare @msg nvarchar(200)
	SET @msg = ('Error during population of data...')

	SELECT
        	ERROR_NUMBER() AS ErrorNumber,
		ERROR_MESSAGE() AS ErrorMessage
		@msg;
END CATCH



Question:
From the C# code, I execute the SP.
If there is an error in the update query, then the C# code does not seem to ge the error_mesage from the SP.
So, should I use the raiserror or something similar instead of the select in the begin catch section?
Thanks

解决方案

use SqlException in Catch section to get Sql error.

try
{
 //Call your SP here
}
catch (SqlException ex)
{
    lblEreMsg.Text = ex.Message;
}
<pre></pre>


Yes actually you handle exception from your stored procedure. So you are not getting that exception from .NET application. Yes you are correct. If your application need to know the exception then you can use raiseerror function.
Raise Error Details

You can also your throw statement. tsql throw Example

declare @i int;
begin try
	set @i = 'a';
end try
begin catch
 print 'Error: ' + error_message();
 throw;
end catch


这篇关于c#/ sql中的错误处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆