TRY..CATCH Block Not Cetching RAISERROR()
Sep 30, 2007
I guess this is a common problem because I ran into a lot of threads concerning the matter. Unfortunately, none of them helped my situation.
I am throw a RAISERROR() in my sql and my vb.net try catch block is not detecting an error.
SELECT '3'
RAISERROR('testerror',10,5)
Dim con As New SqlConnection
Dim _sqlcommand As New SqlCommand
con = New SqlConnection(Spiritopedia.Web.Globals.Settings.General.ConnectionString)
_sqlcommand.CommandType = Data.CommandType.StoredProcedure
_sqlcommand.CommandText = "TestFunction"
_sqlcommand.Connection = con
'The value to be returned
Dim value As New Object
'Execute the command making sure the connection gets closed in the end
Try
'Open the connection of the command
_sqlcommand.Connection.Open()
'Execute the command and get the number of affected rows
'value = _sqlcommand.ExecuteScalar().ToString()
value = _sqlcommand.ExecuteScalar()
Catch ex As SqlException
Throw ex
Finally
'Close the connection
_sqlcommand.Connection.Close()
End Try
View 6 Replies
ADVERTISEMENT
Jun 1, 2006
Hi, I am trying to write a trigger in SQL 2005 and am running into a lot of issues. Here is my code
BEGIN
BEGIN TRY
DECLARE @count int
--check for timeon which is greater than timeoff
SET @count=0
SELECT @count=count(*)
FROM IVRCONFIG.dbo.C_GROUP_HOURS a WITH (NOLOCK),inserted i
WHERE a.XFER_GROUP = i.XFER_GROUP
AND a.DAY_OF_WEEK = i.DAY_OF_WEEK
AND a.TIMEON = i.TIMEON
AND a.TIMEOFF < a.TIMEON
IF @count<>0 RAISERROR (50001,16,1);
END TRY
BEGIN CATCH
RAISERROR
END CATCH
END
The error I specify is one I added to sys.messages. Can anyone tell me where I am going wrong??
View 1 Replies
View Related
Feb 27, 2004
Hi. I am executing a stored procedure. The stored procedure raises an error and all I need is to catch this error. Pretty simple, but it only works with an ExecuteNonQuery and not with an Executereader statement. Can anybody explain to me why this happens?
Here's the sp:
CREATE PROCEDURE dbo.rel_test
AS
select 1
raiserror ('My error.', 11, 2)
return
GO
Here's the ASP.Net page:
<% @Page Language="VB" debug="True" %>
<% @Import Namespace="System.Data.SqlClient" %>
<script runat="server">
Public Function RunSP(ByVal strSP As String) As SqlDataReader
Dim o_conn as SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connectionstring"))
AddHandler o_conn.InfoMessage, New SqlInfoMessageEventHandler(AddressOf OnInfoMessage)
o_conn.Open
Dim cmd As New SqlCommand(strSP, o_conn)
cmd.CommandType = System.Data.CommandType.StoredProcedure
Dim rdr as SqlDataReader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
rdr.Close()
cmd.Dispose()
Response.Write(o_conn.State)
End Function
Private Sub OnInfoMessage(sender as Object, args as SqlInfoMessageEventArgs)
Dim err As SqlError
For Each err In args.Errors
Response.Write(String.Format("The {0} has received a severity {1}, state {2} error number {3}" & _
"on line {4} of procedure {5} on server {6}:{7}", _
err.Source, err.Class, err.State, err.Number, err.LineNumber, _
err.Procedure, err.Server, err.Message))
Next
End Sub
Sub Page_Load(sender as Object, e as EventArgs)
RunSP("rel_test")
End Sub
</script>
View 2 Replies
View Related
May 28, 2008
Is there a reason why the following code does not raise an error in my .NET 2005 application? Basically I have a try..catch in my stored procedure. Then I have a try...catch in my .NET application that I want to display the error message.
But, when the stored proc raisses the error, the .net code doesn't raise it's error. The .NET code DOES raise an error if I remove the try..catch from the SQL proc and let it error (no error handling), but not if I catch the error and then use RAISERROR to bubble-up the error to .NET app. (I really need to catch the error in my SQL proc and rollback the transaction before I raise the error up to my .NET app...)
SQL
BEGIN TRYBEGIN TRANSACTION trnName
DO MY STUFF.... <---- Error raisedCOMMIT TRANSACTION trnName
END TRY
BEGIN CATCHROLLBACK TRANSACTION trnName
RAISERROR('There was an error',10,1)
END CATCH
ASP.NET CODE (No error raised)
Try
daAdapter.SelectCommand.ExecuteNonQuery()Catch ex As SqlException
Err.Raise(50001, "ProcName", "Error:" + ex.Message)
End Try
View 4 Replies
View Related
Dec 11, 2006
HI,
i'm trying to execute some sql using the Try.. Catch blocks.
Following code does not execute in Catch Block
Begin
begin try
insert into dbo.Test values (1,'aaa')
-- here we are inserting int value in identity field...
END TRY
Begin catch
PRINT 'TEST'
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
End
GO
Whereas the following block works fine and the Catch block executes.
Begin
begin try
Select 1/0
--This causes an error.
END TRY
Begin catch
PRINT 'TEST'
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
End
GO
Any idea why is it so?
View 5 Replies
View Related
Apr 12, 2006
Hi:
one of our study group members noticed a strange behavior and has the following question. Any thoughts are appreciated.
I am unable to understand as to why the CATCH block is not executed when an INSERT is made
On table T3 which is dropped after the first transaction.
The severity of Insert into t3 values (3) is Msg 208, Level 16, State 1, Line 2
Invalid object name 't3'.
BOL says TRY€¦CATCH constructs do not trap the following conditions:
Warnings or informational messages with a severity of 10 or lower.
Errors with severity of 20 or higher that terminate the SQL Server Database Engine task processing for the session. If an error occurs with severity of 20 or higher and the database connection is not disrupted, TRY€¦CATCH will handle the error.
Here is the script.
use tempdb
go
create table t1 (a int)
create table t2 (b int)
create table t3 (c int)
Begin tran
Insert into t1 values (1)
Insert into t2 values (2)
Insert into t3 values (3)
IF @@error <> 0
Rollback tran
else
commit tran
-------------------------------------------------------------
Select * from t1
Select * from t2
Select * from t3
-------------------------------------------------------------
Drop table t3
-------------------------------------------------------------
Set xact_abort on
Begin try
Begin tran insertNow
Insert into t1 values (1)
Insert into t2 values (2)
save tran insertNow
Insert into t3 values (3)
commit tran insertNow
End try
Begin Catch
IF (XACT_STATE()) = -1
BEGIN
PRINT 'The transaction is in an uncommittable state.' +
' Rolling back transaction.'
ROLLBACK TRANSACTION insertNow
END;
-- Test if the transaction is active and valid.
IF (XACT_STATE()) = 1
BEGIN
PRINT 'The transaction is committable.' +
' Committing transaction.'
COMMIT TRANSACTION insertNow
END
End Catch
View 9 Replies
View Related
Feb 5, 2008
I have a procedure that executes a sql statement passed in as a parameter. The parameter variable is
@pSqlStatement.
CREATE PROCEDURE [dbo].[ProcedureTest]
@pSqlStatement nvarchar(4000)
AS
BEGIN
DECLARE @retVal int;
BEGIN TRY
EXECUTE sp_executesql @pSqlStatement, N'@ret int OUTPUT', @retVal OUTPUT;
PRINT 'try @retVal = ' + ISNULL(CAST(@retVal AS varchar), 'null');
END TRY
BEGIN CATCH
PRINT 'catch @retVal = ' + ISNULL(CAST(@retVal AS varchar), 'null');
END CATCH;
END;
Here is an example of this procedure being called:
EXECUTE [dbo].[ProcedureTest]
@pSQLStatement = N'EXECUTE @ret = [log].[Log.SetSeverityLevel] 'debug'
Note that in the sp_executesql statement, the @ret variable from the dynamic SQL gets assigned to the local variable @retVal.
Here's the problem; when the procedure [log].[Log.SetSeverityLevel] that gets dynamically executed does a RAISERROR, the code in [dbo].[ProcedureTest] falls through to the catch block in [dbo].[ProcedureTest] as it should, but the value of @retVal is null in the catch block, when the return code in [log].[Log.SetSeverityLevel] is set to -1.
If you comment out BEGIN TRY / END TRY / BEGIN CATCH / END CATCH in [dbo].[ProcedureTest], the value of @retVal is correctly seen as -1. There's something about the TRY CATCH structure that's blowing away @retVal when an error is raised and it falls through to the CATCH block.
Anybody ever seen this before? Is there a workaround?
Thanks - Dana
View 7 Replies
View Related
Oct 10, 2006
Can anyone give a template for a stored procedure which involves a transaction and has a TRY CATCH block too...
Thanks in advance.
View 1 Replies
View Related
Sep 3, 2004
Is there any way to clear out the exception from a previous Try/Catch block if I am nesting another Try/Catch block within it. I am executing a SQL Command and based on the Error number coming back decide whether or not to execute various other Sql commands. Now the Outer exception seems to be taking precedence over the Inner try block, and even though the code is stepped through for the inner try block it is never executed due to the Parent Exception. Is there any way to clear the exception received from the outer Try block? Here is a snippet of code:
Try
Cmd = New SqlCommand(Sql, Con)
Cmd.ExecuteNonQuery()
Catch t as SqlException
if t.Number = "2601" then
sql_upd = "<Text>"
Try
Cmd_upd = New SqlCommand(Sql_upd, Con)
Cmd_upd.ExecuteNonQuery()
Catch b as Exception
response.write("<Text>")
End Try
End If
End Try
Thanks,
View 3 Replies
View Related
Feb 25, 2015
I encountered a werid bug that I can't figure it out in my stored procedure.Here's some sample code the can represent the scenario
Create Proc sp_test
@DeptID Int
as
Begin
Declare @i int=0
Declare @Count int=(Select count(*) from Total)
while(@i<@Count)
[code]....
In the above code Total is a table that has employee name and its department ID and row_number info.The above code should list all employee info that belongs to one DEpt.but after I placed a try catch block the select statement returns no records.If I removed the try catch block it behaves correct.For example If three records reside in the Total table for a certain DeptID.
I expect the outPut will be
Name age salary
Mike 35 $60006
Tom 50 $75000
Frank 55 $120000
View 6 Replies
View Related
May 25, 2008
Can someone please help me figure out why this trigger causes a "Timeout expired" error after the first try? What I'm trying to do is create an incrementing default value for the projectid field. I have a unique index on the field and for some reason, the INSERT statement won't run inside the TRY block, even though the WHILE loop creates a unique id. It's acting like the loop isn't incrementing, but the PRINT statements prove that the loop does work, but the INSERT statement doesn't work after a succesful first try (i.e. NEWPROJ-1 is inserted correctlly). Anyways, any help would be appreciated.
Code Snippet
GO
/****** Object: Trigger [Projects].[CreateID] Script Date: 05/25/2008 14:16:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [Projects].[CreateID]
ON [Projects].[tblProjects]
INSTEAD OF INSERT
AS
DECLARE @projectid varchar(25)
DECLARE @projectname varchar(100)
DECLARE @projectepskey int
DECLARE @maxcount int
SELECT @maxcount = 1
BEGIN
SET NOCOUNT ON;
SELECT @projectname = projectname
FROM inserted
SELECT @projectepskey = projectepskey
FROM inserted
SELECT projectid
FROM Projects.tblProjects
WHERE (projectid = 'NEWPROJ')
IF (@@RowCount = 0)
BEGIN
SELECT @projectid = 'NEWPROJ'
INSERT INTO Projects.tblProjects(projectepskey, projectid, projectname)
VALUES
(@projectepskey, @projectid, @projectname)
END
ELSE
BEGIN
WHILE @maxcount >= 1
BEGIN
BEGIN TRY
SELECT @projectid = 'NEWPROJ-' + CONVERT(varchar, @maxcount)
PRINT @projectid
INSERT INTO Projects.tblProjects(projectepskey, projectid, projectname)
VALUES
(@projectepskey, @projectid, @projectname)
BREAK
END TRY
BEGIN CATCH
SELECT @maxcount = @maxcount + 1
PRINT CONVERT(varchar, @maxcount)
CONTINUE
END CATCH;
END
END
END
View 4 Replies
View Related
Mar 6, 2014
I have a Stored Proc which populates a table and then uses BCP to output the table into a flat file and lastly ftp the file out to a remote site.
I'm trying to update the error handling as I first wrote this script on SQL2000 and it has now moved to SQL2008r2. The stored proc looks something like this:
BEGIN TRY
BEGIN TRANSACTION
<A whole bunch of inserts and updates>
COMMIT TRANSACTION
END TRY
BEGIN CATCH
<Error handling>
ROLLBACK TRANSACTION
END CATCH
BEGIN
<xp_cmdshell, BCP, FTP stuff>
END
What I need to do is jump to the end of the script if an error invokes the CATCH block, so the xp_cmdshell stuff is not exicuted. Can I simply put a GOTO statement to take it to the end in the CATCH block, or do I have to set a variable in the CATCH block then test the variable outside the CATCH block or indeed is there a better way to simply terminate the script following the ROLLBACK?
[URL]
View 7 Replies
View Related
May 3, 2006
When a catchable error occurs in a try block, control is passed to theassociated catch block. While I am then able to examine properties ofthe error using such functions as ERROR_NUMBER() in the catch block,the error-logging scheme used in my company requires that the actualerror be raised so that it can be picked up by components in the nexttier. I appear to be unable to do that -- I can raise some other errorthat has all of the properties of the original except the error number.For example, division by zero raises error 8134. If the code thatproduces that error is enclosed in a try block, I seem to be unable toraise that error from the catch block. Of course, if I never used thetry block to begin with this wouldn't be a problem, but then wewouldn't have the advantages of this structure as it applies to othererrors, some of which we may wish to handle differently. WhileTry-Catch looks great as a way of allowing us to handle errors in acustomized way and to avoid having all errors be passed up to ourmiddle tier, it seems that we are unable to pass ANY such errorsforward, and that is a problem for us, too. Is my understanding ofthis situation correct, or is there some way around this problem, e.g.,is there any way I could have raised error 8134, in the above example?Thanks.
View 2 Replies
View Related
Feb 26, 2008
Hi everybody:
I wanted to handle with the deadlock issue by using Try/Catch, the the try/Catch block cannot capture this kind of deadlock:
code in connection1:
declare @i int
set @i = 0
WHILE (1=1)
begin
ALTER PARTITION SCHEME PartationedTableA NEXT USED [PRIMARY]
ALTER PARTITION FUNCTION PartationedTableA () SPLIT RANGE (14661)
ALTER PARTITION FUNCTION PartationedTableA () MERGE RANGE (14661)
end
code in connection2:
declare @rowcount int
while 1=1
begin
begin try
select @rowcount =count(0) from PartationedTableA where col1=50021
end try
begin catch
print error_number()
end catch
end
run them at the same time in SSMS, the code in cn2 would get a error in several seconds:
Msg 1205, Level 13, State 55, Line 10
Transaction (Process ID 52) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
I tried using TRY/CATCH to capture anoter deadlock whose Error_State is 45, and it works fine.
Does anybody know why Try/Catch cannot capture my deadlock, does the different state make senses?
Thanks.
View 7 Replies
View Related
Dec 10, 2007
I was just debugging a stored procedure visual studio and I was surprised with what I was watching.
I'm running SQL 2005 and visual studio 2005. I have a set of nested try/catch blocks.
It fails on the first try and drops into the catch block just as it should. Within the catch block a dynamic sql statement is created. A try block begins and attempts to exec(@sql). It then drops to the catch block. However, I copy the statement into SQL Management Studio and it runs without error everytime.
Why is it dropping into the catch block? Logically it should just complete executing the statement continue without going into the catch block.
Do I have to reset the raiserror values between try blocks or something?
--Thanks--
View 1 Replies
View Related
Mar 3, 2008
Hello, I have stored procedure that when executed it will check to see if a given name is found in the database, if the name is found, I would like to have it continue on to do its work, however if the name is not found, I would like it to raise an error and then stop execution at that point, however, the way it is currently working is, if the name is not found, it catches the error, raises it and then continues on and tries to do its work, which then it bombs out because it can't. I wasn't sure if there was a way to stop the execution of the procedure in the catch statement. I don't think I want to raise the error level to 20-25 because I don't want to drop the connection to the database per say, I just want to halt execution.
Here is a simple example of what I have:
Code Snippet
begin try
if not exists (select * from sys.database_principals where [name] = 'flea')
raiserror('flea not found', 16, 1)
end try
begin catch
declare @ErrorMessage nvarchar(4000);
declare @ErrorSeverity int;
select
@ErrorMessage = error_message(),
@ErrorSeverity = error_severity();
raiserror(@ErrorMessage, @ErrorSeverity, 1);
end catch
go
begin
print 'hello world'
end
At this point, if the user name (flea) is not found, I don't want it ever to get to the point of 'Hello World', I would like the error raised and the procedure to exit at this point. Any advice would be appreciated on how to best handle my situation!
Thanks,
Flea
View 5 Replies
View Related
Dec 19, 2006
I would like to know if there was any semantic differences between the two following statements?
RAISERROR('Invalid argument.',11,1);
RETURN;
or simply
RAISERROR('Invalid argument.',11,1) WITH NOWAIT;
It seems that both statements interrupt the current transaction.
Does anyone has an idea on the subject?
Thanks in advance,
Joannes
View 4 Replies
View Related
Feb 15, 2007
Hi,
I'm having trouble with a Script Component in a data flow task. I have code that does a SqlCommand.ExecuteReader() call that throws an 'Object reference not set to an instance of an object' error. Thing is, the SqlCommand.ExecuteReader() call is already inside a Try..Catch block. Essentially I have two questions regarding this error:
a) Why doesn't my Catch block catch the exception?
b) I've made sure that my SqlCommand object and the SqlConnection property that it uses are properly instantiated, and the query is correct. Any ideas on why it is throwing that exception?
Hope someone could help.
View 3 Replies
View Related
Dec 3, 2014
I have the following stored procedure to test scope of variables
alter proc updatePrereq
@pcntr int,
@pmax int
as
begin
[Code] ....
In the above script @i is declare in the if block only when the @pcntr value is 1. Assume the above stored procedure is called 5 times from this script
declare @z int
set @z = 1
declare @max int
set @max = 5
while @z <= @max
begin
exec dbo.updatePrereq @z, @max
set @z = @z + 1
end
go
As i said earlier `@i` variable exists only when `@pcntr` is `1`. Therefore when i call the stored procedure for the second time and so forth the control cannot enter the if block therefore @i variable wouldn't even exist. But the script prints the value in `@i` in each iteration, How comes this is possible should it throw an error saying `@i` variable does not exist when `@pcntr` values is greater than `1`?
View 1 Replies
View Related
May 15, 2007
hi all,
All of a sudden my application started crashing when trying execute dml statements on sql server mobile database (sdf file). Frustating thing is that whole application crashes without any error message. this happens for all kinds for DML statement but not all the time. Sometimes it would fail for delete statement such as delete from table; or for insert into statement
my problem catch does not catch the error. There is no way to find out teh what is causing this error
SqlCeConnection sqlcon = new SqlCeConnection("
Data Source = '\Program Files\HISSymbol\HISSymboldb.sdf';"
);
SqlCeCommand sqlcmd = new SqlCeCommand();
sqlcmd.CommandText = Insert into company('AA', 'Lower Plenty Hotel');
sqlcmd.Connection = sqlcon;
SqlCeDataReader sqldr = null;
try
{
sqlcon.Open();
//use nonquery if result is not needed
sqlcmd.ExecuteNonQuery(); // application crashes here
}
catch (Exception e)
{
base.myErrorMsg = e.ToString();
}
finally
{
if (sqlcon != null)
{
if (sqlcon.State != System.Data.ConnectionState.Closed)
sqlcon.Close();
sqlcon.Dispose();
}
}//end of finlally
View 4 Replies
View Related
Jul 12, 2006
In my Windows application I use sqlCmd.ExecuteNonQuery() to execute the stored procedure, In case of an error in the stored procedure I need to return an exception to application, will RAISERROR in stored procedure accomplish that?
View 1 Replies
View Related
Dec 6, 2006
Is there any log regarding RAISERROR and rollback in the SQL Server. I would like to know how many times it happened in a day.
View 1 Replies
View Related
Sep 14, 2007
Hello,I am raising an error on my SQL 2005 procedure as follows: RAISERROR(@ErrorMessage, @ErrorSeverity, 1)How can I access it in my ASP.NET code?Thanks,Miguel
View 1 Replies
View Related
Apr 3, 2001
When I have an raiserror. This is what I got:
Server: Msg 50000, Level 16, State 1, Line 6
No Rows Found for 1 and Rachel.
Question: How do I get rid of this line: "Server: Msg 50000, Level 16, State 1, Line 6"
View 1 Replies
View Related
Jan 14, 2004
Is there a way to raise an exception inside a user function in the Sqlserver2000?.
View 5 Replies
View Related
Jun 14, 2006
hi
RAISERROR is used to return message to the caller.
how to contain RAISERROR :
variable
declare @name varchar(50)
and string
'Welcome'
i want to contain the RAISERROR messege 'Welcome' + @name value in the same time
ex
Welcome Zaid
can give the code to do this
thank you
View 4 Replies
View Related
Apr 16, 2007
hey all,
just cant figure out why my raiserror print
Wrong RoleType for customer lientID
for :- RAISERROR('Wrong RoleType for customer %ClientID', 16,1, @ClientID)
what's with missing C? is % some kind of escape char or something? (im trying to print back the parameter @clientid), or should i just use the print ''
~~~Focus on problem, not solution~~~
View 6 Replies
View Related
Jan 2, 2008
Im working in a Oracle to SQL migration project, I need to migrate a function
which is using Raiserror()
I have a function in Oracle like this,
create function fn_name( parameters )
returns int
as begin
if ( condition )
-- do some logic
else
raiseerror()
end
I need to migrate this to SQL server 2005.
From next version we wont have Extended procedure, so its better to avoid.
Instead that we can use CLR integration.
Can anyone help me out...
View 2 Replies
View Related
Aug 2, 2006
This statement adds a new message to the master..sys.messages table
EXEC sp_addmessage @msgnum = 60000, @severity = 16,
@msgtext = N'The item named %s already exists in %s.'
But if this error happens, how is an application supposed to access this message? (The average app shouldn't need to access to the master database to get this info.)
Barkingdog.
View 1 Replies
View Related
Jul 12, 2006
In my Windows application I use sqlCmd.ExecuteNonQuery() to execute the stored procedure, In case of an error in the stored procedure I need to return an exception to application, will RAISERROR in stored procedure accomplish that?
View 1 Replies
View Related
May 6, 2008
Is there any way to emulate RAISERROR from CLR UDT?
Thanks
View 6 Replies
View Related
Jan 2, 2008
Im working in a Oracle to SQL migration project, I need to migrate a function
which is using Raiserror()
I have a function in Oracle like this,
create function fn_name( parameters )
returns int
as begin
if ( condition )
-- do some logic
else
raiseerror()
end
I need to migrate this to SQL server 2005.
From next version we wont have Extended procedure, so its better to avoid.
Instead that we can use CLR integration.
Can anyone help me out...
View 3 Replies
View Related
Jan 3, 2007
I have used RAISERROR on some of our pages before, and it worked fine. Now I have a page that has a formview with a sqldatasource that does an insert. If the value for a certain field exists already in the table, I am trying to use RAISERROR('message', 15, 1) to have a popup error. The page does a redirect in the iteminserted event. When I try to insert with data that should cause an error, it doesn't insert into the database, but I don't see an error. The page just redirects... any ideas what could be done to fix this?
View 1 Replies
View Related