A very short and straight question: I want to catch the error using try..catch and log it into a file. Is this possible in SQL Server 2008?
Any directions, help are welcome.
Yes, you can.
Just implement try catch as it's described here TRY...CATCH . Error logging can be logged either in application or in sql by writing errors to a table.
If you want to log into a file, you can do that using SQLCLR. Check the answer here
How to log in T-SQL
There're some similar questions you can check.
Logging into table in SQL Server trigger
Best Practices - Stored Procedure Logging
Another approach is to use Log4Sql
View the SQL Server error log by using SQL Server Management Studio or any text editor.
By default, the error log is located at Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG and ERRORLOG.n files.
Go through Viewing the SQL Server Error Log page
Like this, not exactly to file, but to eventlog, I think writing to file is only possible with CLR procedure:
BEGIN TRY
Do some error
END TRY
Begin CATCh
Declare #error nvarchar(max) = error_message()+' your data'
exec master..xp_logevent 50001, #error, 'error'
--Notify host application
RAISERROR(#error, 16, 1)
END CATCH
Related
We have a .NET application (VB / VS2010) and are calling many stored procedures on a SQL Server 2008 for database queries. We also have quite a few update/insert/delete triggers that are executed automatically once these stored procedures modify the database tables.
There are quite often situations when a stored procedure is called and it seems to perform ok as no error is raised and the .NET app continues as usual. However if I then look under the covers and perform the stored procedure call manually via SQL Server Client I see that a trigger that's executed right after the stored procedure fails, thus rolling back all changes.
So my question is: what's the best way to detect and pass through errors in our .NET --> stored procedure --> trigger scenario to know for sure in the .NET app that everything succeeded or not in case of an error?
Many thanks in advance,
Steve
Update: I am at home now and away from my desk (and the code base) for the weekend, so won't have a chance to check the very details of the stored procedures. Thanks so much for the answers given so far. I can have a look at the code again next week.
But in the meantime...
One question was about the version of MS SQL Server: it's 2008.
From what I know out of the top of my head we are calling the stored procedures (at least those that don't read data and "just" update, delete or insert data) in this manner:
Using connection As New SqlConnection("connectionString")
Dim command As New SqlCommand("EXEC STORED_PROCEDUR_ENAME), connection)
command.Connection.Open()
command.ExecuteNonQuery()
End Using
I think the assumption behind the code above is the expectation that if something fails within the stored procedure or a related trigger, that
command.ExecuteNonQuery()
would then fail. That might be my first problem, i.e. will I have to alter this code?
One question below was if I use ExecuteDataReader, so the answer is no, at least not so far...
I'll comment on the SQL specific questions and suggestions below.
I actually had the same issue today,
to solve it i used an output #msg and placed it after each function in the sproc.
SET #msg = 'Test print 1'
each section i added one so i know what ever the last number printed was where the sproc failed. I then went to the table where the trigger was failing and adjusted it until it printed the last number and passed.
You should check ##error after each statement, and return the error if one exists.
Here's a good article for you. Check out the section "Why is My Error Not Raised". It describes a scenario that could be your problem.
http://www.sommarskog.se/error-handling-II.html
You might also want to try turning XACT_ABORT on, so stored procedures would fail for most errors.
EDIT: Here's another link that might help explain this.
http://www.novicksoftware.com/tipsandtricks/tips-erorr-handling-in-a-stored-procedure.htm
You can either return an error from your procedure if you check ##error and find it != 0, or you can use RAISERROR, which will definitely result in an exception in calling code.
http://msdn.microsoft.com/en-us/library/ms178592.aspx
as you mention that you are using sql server 2008. this gives capacity to use try.. catch. here is the article.
http://msdn.microsoft.com/en-us/library/ms175976.aspx
Also look at this forum.
http://social.msdn.microsoft.com/Forums/eu/transactsql/thread/03eae70e-d478-44a7-90f3-8e1d27d9f22e
i think try..catch will do the job. also in .net side i would use following code.
try
{
// your stored procedure execution code.
}
Catch (sqlexception e)
{
// do something with sql exception.
}
try this scenario see if that solves your issue.
I have an issue where I call a stored procedure from a linked server and it times out. However I have no good way of catching this. Though it occurs rarely I am wondering if there is any way to catch this particular warning:
OLE DB provider "SQLNCLI10" for linked server "serverName" returned message "Query timeout expired".
Unfortunatly warnings aren't caught by try/catch and MS does have an open issue that this should be an error: http://connect.microsoft.com/SQLServer/feedback/details/337043/no-error-raised-when-a-remote-procedure-times-out
I don't want to increase the timeout property, and I know I can do something like:
Declare #ret int
select #ret = 4417
Exec #ret=Server.DB.dbo.RemoteSP
If #ret is null afterwards it means the call failed, however it does not tell me exactly what the cause was. Is there anyway to essentially catch that warning? What are the best practices in for remote procedure calls error handling?
As of 2019 there is still no way to properly catch SQL Server remote timeout errors.
It applies both to remote SP calls and constructs like execute ('select 1') at REMOTESQLSERVER.
As per comment from N.Nelu:
Microsoft docs state under "Errors Unaffected by a TRY...CATCH Construct".
Errors Unaffected by a TRY...CATCH Construct
TRY...CATCH constructs do not trap the following conditions:
Warnings or informational messages that have a severity of 10 or
lower.
Errors that have a severity of 20 or higher that stop the SQL Server Database Engine task processing for the session. If an error
occurs that has severity of 20 or higher and the database connection
is not disrupted, TRY...CATCH will handle the error.
Attentions, such as client-interrupt requests or broken client connections.
When the session is ended by a system administrator by using the KILL statement.
Connect link you have provided is dead but you still can vote to fix this feature here. See also this excellent article on SQL Error handling under 4.3 Query Timeout on Linked Servers.
I have a database that I am working on with over 900 SP's. None of the SP's have any error handling. Is there a utility within SQL Server 2005 or 2008 that would automatically log the SP and the error into a table?
If the SPs are being called from code in a separate data layer, you could possibly add a global exception handler for that class. There is no 'global' error handling, per-se in sql server as far as stored procedures go - think about code - in code, if you had a gazillion classes, and there was no ineritance of any sort, you would have to implement error handling on each class separately. Sql server SPs have their own error handling, such as try-catch and ##error - look on books online, or http://www.codeproject.com/KB/database/ErrorHandling.aspx
I am calling the following statement from withing a Stored Proc in SQL Server 2005.
Backup Database #dbname to disk = #dest
I need to be able to store the result of the 'Backup Database' in a variable so if something goes wrong I can kick off an alert to notify someone of the failure.
How can I get that value?
You can execute the Backup Database command within a TRY block I believe. Simply add some code to email the error message in the catch block of the statement.
I am trying to debug a SQL procedure, and am using the following query to do so.
USE [database]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[Populate]
#ssId = 201
SELECT 'Return Value' = #return_value
GO
The problem is, the procedure I am testing, (Populate) doesn't seem to stop at any of the breakpoints I assign to it. Is there a different way to add breakpoints such that I can follow the debugger? I am getting the following error: "Invalid line number specified with SQL breakpoint".
Actually, if you have SQL Server 2008, you can once again debug in Management Studio.
Each of these articles will take you through it step by step, with screenshots. It could hardly be easier.
SQL Server 2008: The Debugger is back
T-SQL Debugger is back in SQL Server 2008 ... debugging now made easy
New Features in SQL Server 2008 Management Studio
Follow these tutorials:
Debugging Stored Procedures in SQL Server 2005
Debugging SQL Server CLR functions, triggers and stored procedures
1 Make a connection to a database.
2 Right-click the stored procedure, user-defined function, or trigger you want to work with and choose Open from the shortcut menu.
To insert a break point
1.Right-click the line of SQL syntax in the editor window where you want to insert a breakpoints.
2.Point to Break point and then click Insert Break point.