Transactions & TRY CATCH Block.

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


ADVERTISEMENT

Try.. Catch Block

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

Try Catch Block

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

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 View Related

Clearing Exception In Catch Block

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

T-SQL (SS2K8) :: Try Catch Block In While Loop

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

TRY...CATCH Block Not Working Properly

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

T-SQL (SS2K8) :: Catch Block With GOTO Statement?

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

Raising Errors In A Catch Block In SQL2005

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

Why The Try/Catch Block Cannot Capture This Kind Of Deadlock?

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

Begin Catch Block Executed When Try Completes Without Error

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

How To Stop Execution Of Stored Procedure If Error Occurs In Try/catch Block

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

Try...catch With Transactions

Apr 28, 2008

I have 3 procedures where the first one calls the second one and the second one calls the third one. All procedures have try..catch blocks and transactions. In the third procedure I declare an INT variable and try to give it the value 'A', to create an error. This makes the code in the catch block to run. In the catch block I rollback the transaction and return 1. It then returns to the 2nd procedure, but here I get the exception "Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 2, current count = 0. Is there I way to keep running the code in the second procedure without getting this error? I take care of the return value from the 3rd procedure which is 1 so I know that there was an error in the third procedure but I want to run the code below the procedure call to the 3rd procedure in the second procedure, is there I way to do this?

I tried to have a transaction only in the first procedure but then I get this error "The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction."

What shoule I do to continue running the code in procedure 2 and procedure 1 after the procedure calls? In real life I have another scenario but the code below is just an easy example that creates the same error that my real procedures create.

Procedure 1:





Code Snippet
ALTER PROCEDURE [dbo].[ProcFirst]
AS
BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
BEGIN TRY

DECLARE @return int
BEGIN TRANSACTION




EXEC @return = [dbo].[ProcSecond]
IF @return <> 0
BEGIN

SELECT 'return value <> 0 i ProcFirst'
RETURN 1
END
IF (XACT_STATE()) = 1 COMMIT TRANSACTION
RETURN 0

END TRY
BEGIN CATCH -- Error-handling statements


-- End Transaction
IF @@TRANCOUNT > 0 BEGIN

IF (XACT_STATE()) = -1 ROLLBACK TRANSACTION;
IF (XACT_STATE()) = 1 COMMIT TRANSACTION;
END


SELECT 'catch ProcFirst', @ErrorMessage


RETURN 1

END CATCH
END






Procedure 2:




Code Snippet
ALTER PROCEDURE [dbo].[ProcSecond]
AS
BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
BEGIN TRY

DECLARE @return int
BEGIN TRANSACTION




EXEC @return = [dbo].[ProcThird]




IF @return <> 0
BEGIN

-- End Transaction
IF @@TRANCOUNT > 0
BEGIN

IF (XACT_STATE()) = -1
BEGIN

SELECT 'RollBack transaction'
ROLLBACK TRANSACTION;
END
IF (XACT_STATE()) = 1
BEGIN

Select 'commit transaction'
COMMIT TRANSACTION;
END
END
SELECT 'return value <> 0 i ProcSecond'
RETURN 1
END



IF (XACT_STATE()) = 1 COMMIT TRANSACTION
RETURN 0
END TRY
BEGIN CATCH -- Error-handling statements

-- End Transaction
IF @@TRANCOUNT > 0
BEGIN

IF (XACT_STATE()) = -1 ROLLBACK TRANSACTION;
IF (XACT_STATE()) = 1 COMMIT TRANSACTION;
END



SELECT 'catch ProcSecond', @ErrorMessage



RETURN 1
END CATCH
END






3rd procedure:




Code Snippet
ALTER PROCEDURE [dbo].[ProcThird]
AS
BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
BEGIN TRY

DECLARE @tal int
BEGIN TRANSACTION




SET @Tal = 'a'
IF (XACT_STATE()) = 1 COMMIT TRANSACTION;
RETURN 0
END TRY
BEGIN CATCH -- Error-handling statements
--End Transaction

IF @@TRANCOUNT > 0
BEGIN

IF (XACT_STATE()) = -1
BEGIN

SELECT 'RollBack transaction ProcThird'
ROLLBACK TRANSACTION;
END
IF (XACT_STATE()) = 1
BEGIN

Select 'commit transaction ProcThird'
COMMIT TRANSACTION;
END
END



RETURN 1
END CATCH
END






Please help me!

//Emelia

View 4 Replies View Related

Try Catch Doesn't Catch Errors Inside A Data Flow Transformation Script Component

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

T-SQL (SS2K8) :: Why Block Scope Variables Exist Outside Of Block

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

Try Catch Does Not Catch Exception

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

Changing Connection Transactions To Database Transactions

May 22, 2005

Hi there,
I have decided to move all my transaction handling from asp.net to stored procedures in a SQL Server 2000 database. I know the database is capable of rolling back the transactions just like myTransaction.Rollback() in asp.net. But what about exceptions? In asp.net, I am used to doing the following:
<code>Try   'execute commands   myTransaction.Commit()Catch ex As Exception   Response.Write(ex.Message)   myTransaction.Rollback()End Try</code>Will the database inform me of any exceptions (and their messages)? Do I need to put anything explicit in my stored procedure other than rollback transaction?
Any help is greatly appreciated

View 3 Replies View Related

Pl/Sql Block?

Apr 8, 2008

I've written a couple blocks but I have no idea when it comes to this one.
Create a PL/SQL block to retrieve the last name and department ID if each employee from the EMPLOYEES table
for those employees whose EMPLOYEE_ID is less than 114. From the values retreived from the employees table, populate two PL/SQL tables,
one to store the records of the employee last names and the other to store the records of their department IDs.
Using a loop, retreive the employee name information and salary infromation from the PL/SQL tables and doisplay it in the window,
using DBMS_OUTPUT.PUT_LINE. Display these details for the first 15 employees in the PL/SQL tables.
Any help helps

View 1 Replies View Related

AES (128 Bit Block) : Can I Use It?

May 18, 2006

If I've got a 64-bit OS such as Windows XP Professional x64 Edition running and I have the SQL Server 2005 Express Edition, is AES permittable or does TRIPLEDES still need to be used?

View 1 Replies View Related

Try Catch

Jan 15, 2007

Hi

for MS SQL 2000
how can I do ?:


INSERT INTO [Users] (Name)
SELECT Names FROM OtherUsers


I am having an UNIQUE INDEX on [Users].Name

how can I avoid an error ?
if the [Users].Name allready exists I want to jump over the error and keep on inserting

thank you for helping

View 14 Replies View Related

TRY CATCH

Apr 22, 2008

Is it any better than using @@ERROR?

It doesn't seem so

Any opinions?



Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Add yourself!
http://www.frappr.com/sqlteam

View 4 Replies View Related

Try Catch

May 13, 2008

Hi!

I'm trying to use Try Catch together with transaction handling but it seems like it doesn't do Rollback although I produce an error.

It looks something like this:


DECLARE @soID INT
BEGIN TRY
BEGIN TRANSACTION
UPDATE Serviceobjekt
SET ServiceobjektstypID = 13
WHERE ServiceobjektID = 26555

UPDATE .... 2 more tables

INSERT INTO Serviceobjekt (
Namn...)
VALUES ('XXXX')

SET @soID = @@IDENTITY
INSERT INTO Atgard (
Namn, ServiceobjektID)
VALUES ('sssss',@soID)

COMMIT TRANSACTION
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH


I get after changing some id's in the where clause which I know is wrong I get a result like this:

(0 row(s) affected)

(0 row(s) affected)

(1 row(s) affected)

(0 row(s) affected)

Shouldn't it be 0 rows affected on all if just one update or insert statement is wrong?

/Magnus

View 4 Replies View Related

Try And Catch

May 22, 2008

Hi I use Try catch and transactions in one of my stored procedures.

Inside I make a call to another stored procedure.

Is it possible to roll back the outer sp?

Please advise.

View 1 Replies View Related

Catch Me If You Can / Bug In The Bug?

Oct 7, 2007

Hello!
Try this (-:

BEGIN TRY

SELECT *

FROM NonExistentTable ;

END TRY

BEGIN CATCH

PRINT 'catch me if you can' ;

END CATCH ;

/*

results in:

Msg 208, Level 16, State 1, Line 2

Invalid object name 'NonExistentTable'.

statement not printet */

BEGIN TRY

BEGIN TRY

SELECT *

FROM NonExistentTable ;

END TRY

BEGIN CATCH

PRINT 'catch me if you can' ;

END CATCH ;

END TRY

BEGIN CATCH

PRINT 'catched?'

END CATCH ;

-- same behaviour

CREATE PROC catchme

AS

BEGIN

BEGIN TRY

SELECT *

FROM nonexistingtable ;

END TRY

BEGIN CATCH

PRINT 'catch me if you can'

END CATCH ;

END ;

BEGIN TRY

EXEC catchme ;

END TRY

BEGIN CATCH

PRINT 'catched' ;

END CATCH ;

-- prints "catched"

BEGIN TRY

EXEC catchnonexistingproc ;

END TRY

BEGIN CATCH

PRINT 'catched again' ;

SELECT error_state()

END CATCH ;

-- prints "catched again"





BEGIN TRY

RAISERROR ('catch this' , 10 , 1) ;

END TRY

BEGIN CATCH

PRINT 'hello' ;

END CATCH ;

-- no hello

BEGIN TRY

RAISERROR ('catch this' , 11 , 1) ;

END TRY

BEGIN CATCH

PRINT 'hello' ;

END CATCH ;

-- prints hello



CREATE PROC catchme2

AS

BEGIN

BEGIN TRY

RAISERROR ('catch this' , 10 , 1) ;

END TRY

BEGIN CATCH

PRINT 'CATCH ME IF YOU CAN' ;

END CATCH ;

END ;



BEGIN TRY

EXEC catchme2 ;

END TRY

BEGIN CATCH

PRINT 'gotcha?' ;

END CATCH ;

-- prints only "catch this"





CREATE PROC catchme3

AS

BEGIN

BEGIN TRY

RAISERROR ('catch this' , 20 , 1) ;

END TRY

BEGIN CATCH

PRINT 'CATCH ME IF YOU CAN' ;

END CATCH ;

END ;

BEGIN TRY

EXEC catchme3 ;

END TRY

BEGIN CATCH

PRINT 'gotcha?' ;

END CATCH ;

-- prints "CATCH ME IF YOU CAN" ;-)

See also
-- ms-help://MS.SQLCC.v9/MS.SQLSVR.v9.en/udb9/html/3a5711f5-4f6d-49e8-b1eb-53645181bc40.htm

The above behaviour is as described in BOL, but
comparing to other languages such as Java, C#, PL/SQL
I would expect that catch always catch unless you take the power from the machine, special
in the case for "catchnonexistingproc". Remark the different behaviour compared to "nonexistingtable"
Documentation shows not example for non existing proc!
That catch doesn't catch "is as bug". So is the catch of non existing proc a bug in the bug? ;^)
I hope not, because it is the behaviour we want...

Greetings




View 7 Replies View Related

Database Block

Apr 10, 2008

Hello,

I have been experiencing a lot of blocking activity in my database. My trace results show that the following extended stored procedures sp_prepexec and sp_cursorfetch are executed by both the user causing the block and the user tha is blocked. Any ideas as to how to rectify this situation will be appreciated.

Regards,

Albert

View 3 Replies View Related

How To Check Block

Mar 5, 2008

Can anyone guide me to write check block in SQL Server?
I Mean if blocking occurs, just inform people.

View 3 Replies View Related

Table Block

Mar 18, 2008

Hi there! I need such thing: I have a data in Table A. When I get this data, I also increment this data by one, what I want is block Table A in order to other people will not get access to data.. I think about transactions, but are transactions reaaly blocks a table's content?
P.S. For example in MySQL there are Lock table command for blocking table for reading/writing. I need such thing/
Thanks

View 8 Replies View Related

Process Block Itself

Jul 3, 2007

Hi to everybody,

i have this problem.

sometimes a process in my SQL Server 2005 (upd 2) is blocked from itself. If I find in monitor it wait for a lock_M_Sch_M on a temporary table as you can see from

select * from sys.dm_tran_locks where request_session_id=51 and request_status <> 'GRANT'



resorce type : OBJECT

resource id : 218899226

request mode : Sch-M

request status WAIT

request_session id : 51

request life time : 33554432



or from

SELECT * FROM sys.dm_os_waiting_tasks WHERE SESSION_ID=51



waiting task address : 0x0000000000C2F198

session id : 51

wait type : LCK_M_SCH_M

resource address : 0x0000000201C71300

blocking task address : 0x0000000000C2F198

blocking session id = 51

resource description objectlock lockPartition=0 objid=218899226 subresource=FULL dbid=2 id=lock80d04900 mode=Sch-S associatedObjectId=218899226



I resolve this problem only with restart of sql server . that clear tempdb and eliminate this process



I think is not a problem about latch present from sql server 2000 sp4 (I read some document abount this problem)



So I haven't idea how to resolve this problem and how to kill this kind of process without to restart sql server



thanks in advance



Luca







View 4 Replies View Related

How Do We Use Block Cursor

Oct 25, 2007



hi there,
to retrieve more then one record with a cursor we can use block cursor, so we have to set the cursor attribute SQL_ATTR_ROWSET_SIZE to some number...i am not getting any code example on this.
do anyone know this???

View 6 Replies View Related

Try And Catch Problem

Feb 26, 2007

I want to use a try/catch to catch any error with this datareader so if no data then exit sub, eventually I will create custom error pagebut for now I just want to exit sub so following sql statements are not executed. I get the following problem  when I try to close connection.this was not a problem before using try and catch, do I have in right place? Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load        'declare vars        Dim iPreqid As String = CStr(Session("iPreqid"))                Dim sql As String = "select  *  from Vrequest where req_id = '" & iPreqid & "'"        'Connection String  value        Dim conn As String = ConfigurationManager.ConnectionStrings("LoansConnectionString").ConnectionString        'Create a SqlConnection instance        Using myConnection As New SqlConnection(conn)            Dim myCommand As New SqlCommand(sql, myConnection)            'declare sqldatareader            Dim dbReader As SqlDataReader            Try                myConnection.Open()                myCommand.ExecuteNonQuery()                dbReader = myCommand.ExecuteReader                'Initialize reader                dbReader.Read()                'assign reader index values using column names to controls                Label8.Text = CStr(dbReader("User_Name"))                Label11.Text = CStr(dbReader("NHI"))                Label9.Text = CStr(dbReader("Event_Number"))                Label10.Text = CStr(dbReader("ACC_Number"))                Label7.Text = CStr(dbReader("Required_Date"))                Label1.Text = CStr(dbReader("Title"))                Label3.Text = CStr(dbReader("address1"))                Label4.Text = CStr(dbReader("Birth_date"))                Label2.Text = CStr(dbReader("surname"))                Label5.Text = CStr(dbReader("home_phone"))                Label21.Text = CStr(dbReader("firstname"))                Label20.Text = CStr(dbReader("delivery"))                Label22.Text = CStr(dbReader("ward"))                Label23.Text = CStr(dbReader("request_date"))            Catch ex As Exception                Session("exception") = ex                exit sub            End Try        End Using        'if connection not closed then close        If (Not conn Is Nothing) Then            myConnection.Close()<---------------------------------------->Name 'myconnection is not declared'            myConnection.Dispose()<---------------------------------------->Name 'myconnection is not declared'        End If

View 4 Replies View Related

Try,Catch And Response

Jul 2, 2007

Hi,
Here is the code:Try
If DS.Tables(0).Rows.Count = 0 ThenResponse.Write("Cannot delete an unexist row!")
Response.End()
End If
DS.Tables(0).Rows(0).Delete()
Catch BUG as Exception
Response.Write(Bug.Message)
End Try
I removed all the connection stuff..
What I don't understand is why if ds.table(0).rows.count is zero I still get Bug.Message? I did Response.End ...
Thank you.

View 11 Replies View Related

Help Using Try Catch Exception Please

Mar 25, 2008

  Protected Sub detailsview1_ItemDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewDeleteEventArgs)
Dim label2 As Label = CType(detailsview1.FindControl("label2"), Label)
Try

Catch sqlEx As SqlClient.SqlException
If sqlEx.Message.Contains("DELETE statement conflicted with COLUMN REFERENCE") Then
label2.Visible = True
label2.Text = "You cannot delete this Agent Type as it has a call weighting assigned to it, remove the weightings before you try to delete it"
e.Cancel = True
End If
End Try
End Sub Hi, Im using vb.net sql2005 and visual studio 2005
I have 2 tables which have a foregin key relationship.  When i try to delete information from within one of my aspx pages it rightly comes up with an application errror, something along the lines of
 DELETE statement conflicted with COLUMN REFERENCE constraint 'FK_callScore_agentType'. The conflict occurred in database 'Merlin_####', table 'callScores', column 'typeID'.The statement has been terminated.
I have looked around and can see people talking about using a try catch excpetion however i need to know how id implement this using the detailsview1_itemdeleting event. Ive never used this before and havent found a decent tutorial to help.So far i have this code but im stuck as im not sure that this is correct but more importantly what i put in the try method. Protected Sub detailsview1_ItemDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewDeleteEventArgs)
Dim label2 As Label = CType(detailsview1.FindControl("label2"), Label)
Try
(WHAT GOES HERE)
Catch sqlEx As SqlClient.SqlException
If sqlEx.Message.Contains("DELETE statement conflicted with COLUMN REFERENCE") Then
label2.Visible = True
label2.Text = "You cannot delete this Agent Type as it has a call weighting assigned to it, remove the weightings before you try to delete it"
e.Cancel = True
End If
End Try
End Sub Your help would be greatly appreciated

View 12 Replies View Related

SP Catch Error

Aug 21, 2007

Hi,

I have the following stored procedure which is added to the windows scheduler. When it is run I'm getting an "Invalid use of null error", therefore I need to capture and any errors but I'm not sure how to do this. Can someone help?
Thanks.


Code:

CREATE PROCEDURE [dbo].[usp_Reminders] AS

DECLARE @ReminderSent datetime
DECLARE @getRecords CURSOR
DECLARE @err int

SELECT E.[RL Staff No], E.Forename, E.Surname, C.CourseName, V.CourseDate , E.Email, V.ReminderSent
FROM empdetails.dbo.v_Employee E
INNER JOIN Validation V ON E.[RL Staff No] = V.[RL Staff No]
INNER JOIN empdetails.dbo.v_Course C ON V.CourseCode = C.CourseCode
WHERE V.Completed Is Null AND V.ReminderSent Is Null AND V.CourseDate <= dateadd(dd, -3, getdate())
order by e.[rl staff no]

SET @getRecords = CURSOR FOR

SELECT V.ReminderSent
FROM empdetails.dbo.v_Employee E
INNER JOIN Validation V ON E.[RL Staff No] = V.[RL Staff No]
INNER JOIN empdetails.dbo.v_Course C ON V.CourseCode = C.CourseCode
WHERE V.Completed IS NULL AND V.ReminderSent IS NULL AND V.CourseDate <= dateadd(dd, -3, getdate())
ORDER BY e.[rl staff no]

OPEN @getRecords
FETCH NEXT FROM @getRecords INTO @ReminderSent
WHILE @@FETCH_STATUS= 0
BEGIN
UPDATE Validation
SET ReminderSent = GetDate()
WHERE CURRENT OF @getRecords
FETCH NEXT FROM @getRecords INTO @ReminderSent
END

CLOSE @getRecords
DEALLOCATE @getRecords
GO

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved