从存储过程中获取调用.NET应用程序的Error_Number()
本文关键字:Error Number 应用程序 NET 存储过程 存储 过程中 获取 调用 | 更新日期: 2023-09-27 18:24:30
嗨,将Error_Number()
从存储过程传递到调用.NET应用程序的最佳方式是什么?
我知道我们可以通过设置输出参数或通过SELECT
查询来实现。
注意:我使用的是数据读取器。
提前谢谢。
您可以尝试这样做-在SQL try/catch
块中捕获Error_number()
,然后引发一个错误,您可以在.NET应用程序中捕获该错误作为SqlException
。
在SQL存储过程中:
BEGIN TRY
-- do something here....
END TRY
BEGIN CATCH
DECLARE @ErrorNumber INT
SELECT @ErrorNumber = ERROR_NUMBER()
RAISERROR
(N'The error code is: %d',
16, -- Severity.
1, -- State.
@ErrorNumber, -- First substitution argument.
''); -- Second substitution argument.
END CATCH;
以及在您的.NET代码中(此处:C#):
// call your stored proc some way...
using(SqlConnection conn = new SqlConnection("server=.;database=Test;Integrated Security=SSPI;"))
using (SqlCommand cmd = new SqlCommand("dbo.YourStoredProcNameHere", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// possibly add parameters to the stored procedure call....
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch (SqlException ex)
{
// catch SqlException - ex.ErrorNumber contains your error number
string msg = string.Format("Error number: {0} / Message: {1}", ex.Number, ex.Message);
}
}
试试这个:
BEGIN TRY
-- Generate a constraint violation error.
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;