 |
|
 |
|
Next: Inconsistent Behaviour in ime Comparison Calculat..
|
| Author |
Message |
External

Since: Jan 12, 2008 Posts: 11
|
(Msg. 1) Posted: Fri Dec 19, 2008 3:31 am
Post subject: Some questions about Stored Procedures, Error Handling,Transactions... Archived from groups: microsoft>public>sqlserver>programming (more info?)
|
|
|
Hi, I have a stored procedure like this:
---------------------------------------------------------
PROCEDURE dbo.SPGravaAgendaProf
@CodProf int,
@Usuario uniqueidentifier,
@CodEspec int,
@Dt_Inicio date,
@Dt_Fim date,
@Hora_Inicio time(7),
@Qtd int,
@Intervalo time(7),
@Err nvarchar(2048) output
AS
begin tran
BEGIN try
declare @id_agenda int;
insert into Agendas (Cod_Tipo_Agenda) values (1);
select @id_agenda = SCOPE_IDENTITY();
INSERT INTO Agendas_Profissional
(Cod_Agenda, Cod_Especialidade, Cod_Profissional,
Dt_Inicio, Dt_Fim, Hora_Inicio, Qtd, Intervalo, Ativa)
VALUES (@Id_Agenda,@CodEspec,@CodProf,@Dt_Inicio,
@Dt_Fim,@Hora_Inicio,@Qtd,@Intervalo,0);
INSERT INTO Log_Agendas
(Id_Agenda, Dt_Hora, usuario, Id_Tp_Entrada)
VALUES (@id_agenda,GETDATE(),@Usuario,1)
commit;
return 1;
end try
begin catch
select @err = error_message();
rollback;
RETURN 0;
end catch;
-------------------------------------------------------
And I have some questions, and hope that you guys can help me...
1 - Is this the best way to handle error and return the error to the
application?
2 - The transaction is right? I'm having an issue that when the first
insert goes ok and the second or third goes wrong, the identity column
of the Agenda table is incremented, and then when I insert another row,
it jumps to the next identity number, and stay a hole between number,
like 1,3,4,6....
3 - If I create a Stored Procedure to handle the insert of the log table
and call this procedure instead of the third insert, will this sp be in
the transaction of this procedure?
Thanks...
*** Sent via Developersdex http://www.developersdex.com *** >> Stay informed about: Some questions about Stored Procedures, Error Handling,Tra.. |
|
| Back to top |
|
 |  |
External

Since: Jan 10, 2008 Posts: 640
|
(Msg. 2) Posted: Fri Dec 19, 2008 4:42 am
Post subject: Re: Some questions about Stored Procedures, Error [Login to view extended thread Info.] Archived from groups: per prev. post (more info?)
|
|
|
On Dec 19, 5:31 am, Ricardo Luceac wrote:
> Hi, I have a stored procedure like this:
>
> ---------------------------------------------------------
> PROCEDURE dbo.SPGravaAgendaProf
> @CodProf int,
> @Usuario uniqueidentifier,
> @CodEspec int,
> @Dt_Inicio date,
> @Dt_Fim date,
> @Hora_Inicio time(7),
> @Qtd int,
> @Intervalo time(7),
> @Err nvarchar(2048) output
> AS
> begin tran
> BEGIN try
> declare @id_agenda int;
> insert into Agendas (Cod_Tipo_Agenda) values (1);
> select @id_agenda = SCOPE_IDENTITY();
> INSERT INTO Agendas_Profissional
> (Cod_Agenda, Cod_Especialidade, Cod_Profissional,
> Dt_Inicio, Dt_Fim, Hora_Inicio, Qtd, Intervalo, Ativa)
> VALUES (@Id_Agenda,@CodEspec,@CodProf,@Dt_Inicio,
> @Dt_Fim,@Hora_Inicio,@Qtd,@Intervalo,0);
> INSERT INTO Log_Agendas
> (Id_Agenda, Dt_Hora, usuario, Id_Tp_Entrada)
> VALUES (@id_agenda,GETDATE(),@Usuario,1)
> commit;
> return 1;
> end try
> begin catch
> select @err = error_message();
> rollback;
> RETURN 0;
> end catch;
> -------------------------------------------------------
>
> And I have some questions, and hope that you guys can help me...
>
> 1 - Is this the best way to handle error and return the error to the
> application?
>
> 2 - The transaction is right? I'm having an issue that when the first
> insert goes ok and the second or third goes wrong, the identity column
> of the Agenda table is incremented, and then when I insert another row,
> it jumps to the next identity number, and stay a hole between number,
> like 1,3,4,6....
There is no easy way to get rid of gaps.
>
> 3 - If I create a Stored Procedure to handle the insert of the log table
> and call this procedure instead of the third insert, will this sp be in
> the transaction of this procedure?
>
Yes it will.
excellent artcile:
http://www.sommarskog.se/error-handling-I.html
the convention is to return 0 on success, errror code on failure. >> Stay informed about: Some questions about Stored Procedures, Error Handling,Tra.. |
|
| Back to top |
|
 |  |
External

Since: Jun 18, 2008 Posts: 29
|
(Msg. 3) Posted: Fri Dec 19, 2008 7:36 am
Post subject: Re: Some questions about Stored Procedures, Error Handling,Transactions... [Login to view extended thread Info.] Archived from groups: per prev. post (more info?)
|
|
|
I don't have time at the moment to answer your other questions (fleeting
look-in on the newsgroup), but on the id_agenda incrementation, as Celko is
likely to point out at some point, an IDENTITY column is incremented for
each 'physical insertion attempt', or in other words, it increases even if
the actual insertion fails. This means that if you have failed insertions,
you will get gaps in id_agenda.
Yours,
Ann-Marie
"Ricardo Luceac" wrote in message
>
>
> Hi, I have a stored procedure like this:
>
>
> ---------------------------------------------------------
> PROCEDURE dbo.SPGravaAgendaProf
> @CodProf int,
> @Usuario uniqueidentifier,
> @CodEspec int,
> @Dt_Inicio date,
> @Dt_Fim date,
> @Hora_Inicio time(7),
> @Qtd int,
> @Intervalo time(7),
> @Err nvarchar(2048) output
> AS
> begin tran
> BEGIN try
> declare @id_agenda int;
> insert into Agendas (Cod_Tipo_Agenda) values (1);
> select @id_agenda = SCOPE_IDENTITY();
> INSERT INTO Agendas_Profissional
> (Cod_Agenda, Cod_Especialidade, Cod_Profissional,
> Dt_Inicio, Dt_Fim, Hora_Inicio, Qtd, Intervalo, Ativa)
> VALUES (@Id_Agenda,@CodEspec,@CodProf,@Dt_Inicio,
> @Dt_Fim,@Hora_Inicio,@Qtd,@Intervalo,0);
> INSERT INTO Log_Agendas
> (Id_Agenda, Dt_Hora, usuario, Id_Tp_Entrada)
> VALUES (@id_agenda,GETDATE(),@Usuario,1)
> commit;
> return 1;
> end try
> begin catch
> select @err = error_message();
> rollback;
> RETURN 0;
> end catch;
> -------------------------------------------------------
>
> And I have some questions, and hope that you guys can help me...
>
> 1 - Is this the best way to handle error and return the error to the
> application?
>
> 2 - The transaction is right? I'm having an issue that when the first
> insert goes ok and the second or third goes wrong, the identity column
> of the Agenda table is incremented, and then when I insert another row,
> it jumps to the next identity number, and stay a hole between number,
> like 1,3,4,6....
>
> 3 - If I create a Stored Procedure to handle the insert of the log table
> and call this procedure instead of the third insert, will this sp be in
> the transaction of this procedure?
>
> Thanks...
>
>
> *** Sent via Developersdex http://www.developersdex.com *** >> Stay informed about: Some questions about Stored Procedures, Error Handling,Tra.. |
|
| Back to top |
|
 |  |
External

Since: Apr 11, 2007 Posts: 60
|
(Msg. 4) Posted: Fri Dec 19, 2008 9:59 am
Post subject: RE: Some questions about Stored Procedures, Error Handling,Transaction [Login to view extended thread Info.] Archived from groups: per prev. post (more info?)
|
|
|
Concerning your first question, the CATCH block as you have it will not
return the error to the application. You need to explicitly execute RAISERROR
within the CATCH block to have your application see it. You can create a more
meaningful message to be returned using various system functions like
ERROR_NUMBER(), ERROR_SEVERITY(), ERROR_STATE(), ERROR_LINE(),
ERROR_PROCEDURE(), and ERROR_MESSAGE().
Vern Rabe
"Ricardo Luceac" wrote:
>
>
> Hi, I have a stored procedure like this:
>
>
> ---------------------------------------------------------
> PROCEDURE dbo.SPGravaAgendaProf
> @CodProf int,
> @Usuario uniqueidentifier,
> @CodEspec int,
> @Dt_Inicio date,
> @Dt_Fim date,
> @Hora_Inicio time(7),
> @Qtd int,
> @Intervalo time(7),
> @Err nvarchar(2048) output
> AS
> begin tran
> BEGIN try
> declare @id_agenda int;
> insert into Agendas (Cod_Tipo_Agenda) values (1);
> select @id_agenda = SCOPE_IDENTITY();
> INSERT INTO Agendas_Profissional
> (Cod_Agenda, Cod_Especialidade, Cod_Profissional,
> Dt_Inicio, Dt_Fim, Hora_Inicio, Qtd, Intervalo, Ativa)
> VALUES (@Id_Agenda,@CodEspec,@CodProf,@Dt_Inicio,
> @Dt_Fim,@Hora_Inicio,@Qtd,@Intervalo,0);
> INSERT INTO Log_Agendas
> (Id_Agenda, Dt_Hora, usuario, Id_Tp_Entrada)
> VALUES (@id_agenda,GETDATE(),@Usuario,1)
> commit;
> return 1;
> end try
> begin catch
> select @err = error_message();
> rollback;
> RETURN 0;
> end catch;
> -------------------------------------------------------
>
> And I have some questions, and hope that you guys can help me...
>
> 1 - Is this the best way to handle error and return the error to the
> application?
>
> 2 - The transaction is right? I'm having an issue that when the first
> insert goes ok and the second or third goes wrong, the identity column
> of the Agenda table is incremented, and then when I insert another row,
> it jumps to the next identity number, and stay a hole between number,
> like 1,3,4,6....
>
> 3 - If I create a Stored Procedure to handle the insert of the log table
> and call this procedure instead of the third insert, will this sp be in
> the transaction of this procedure?
>
> Thanks...
>
>
> *** Sent via Developersdex http://www.developersdex.com ***
> >> Stay informed about: Some questions about Stored Procedures, Error Handling,Tra.. |
|
| Back to top |
|
 |  |
External

Since: Aug 20, 2008 Posts: 672
|
(Msg. 5) Posted: Fri Dec 19, 2008 10:52 am
Post subject: Re: Some questions about Stored Procedures, Error Handling,Transactions... [Login to view extended thread Info.] Archived from groups: per prev. post (more info?)
|
|
|
When working with transaction and error handling it is good to have
correct nesting level (like the whole transaction inside TRY.. CATCH).
Also, in the CATCH block you can check XACT_STATE to do proper commit or
rollback. Here is a skeleton:
BEGIN TRY
BEGIN TRAN
-- your code here
COMMIT TRAN
END TRY
BEGIN CATCH
IF (XACT_STATE()) = -1
BEGIN
-- open transaction but uncommittable
ROLLBACK
END
ELSE IF (XACT_STATE()) = 1
BEGIN
-- open and committable
COMMIT -- or ROLLBACK
END
ELSE
BEGIN
-- There are no open transactions
END
END CATCH
If you make the third insert statement a stored procedure, then it is
still inside the transaction and on rollback the changes by the stored
procedure will be undone.
--
Plamen Ratchev
http://www.SQLStudio.com >> Stay informed about: Some questions about Stored Procedures, Error Handling,Tra.. |
|
| Back to top |
|
 |  |
External

Since: May 30, 2004 Posts: 2060
|
(Msg. 6) Posted: Fri Dec 19, 2008 3:45 pm
Post subject: Re: Some questions about Stored Procedures, Error Handling,Transactions... [Login to view extended thread Info.] Archived from groups: per prev. post (more info?)
|
|
|
Ricardo Luceac ( ) writes:
> @Err nvarchar(2048) output
> end try
> begin catch
> select @err = error_message();
> rollback;
> RETURN 0;
> end catch;
> -------------------------------------------------------
>
> And I have some questions, and hope that you guys can help me...
>
> 1 - Is this the best way to handle error and return the error to the
> application?
It would be more common to re-raise the error, rather than returning
an output parameter. But as long as the application knows what to
look for, that's OK.
However, you should set @err to NULL initially, in case the caller
inadverently passes something in @err.
> 2 - The transaction is right? I'm having an issue that when the first
> insert goes ok and the second or third goes wrong, the identity column
> of the Agenda table is incremented, and then when I insert another row,
> it jumps to the next identity number, and stay a hole between number,
> like 1,3,4,6....
It's the nature of IDENTITY. It behaves that way to alleviate concurrency.
If you cannot accept gaps, don't use IDENTITY.
> 3 - If I create a Stored Procedure to handle the insert of the log table
> and call this procedure instead of the third insert, will this sp be in
> the transaction of this procedure?
Yes.
--
Erland Sommarskog, SQL Server MVP, esquel.DeleteThis@sommarskog.se
Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
SQL 2000: http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx >> Stay informed about: Some questions about Stored Procedures, Error Handling,Tra.. |
|
| Back to top |
|
 |  |
External

Since: Feb 11, 2008 Posts: 24
|
(Msg. 7) Posted: Mon Dec 22, 2008 1:43 am
Post subject: Re: Some questions about Stored Procedures, Error [Login to view extended thread Info.] Archived from groups: per prev. post (more info?)
|
|
|
Plamen,
in the section "your code here" you have no examples.
I think there needs to be something like this:
BEGIN TRY
BEGIN TRAN
exec MySpecialSproc
COMMIT TRAN
END TRY
BEGIN CATCH
IF (XACT_STATE()) = -1
BEGIN
-- open transaction but uncommittable
ROLLBACK
END
ELSE IF (XACT_STATE()) = 1
BEGIN
-- open and committable
COMMIT -- or ROLLBACK
END
ELSE
BEGIN
-- There are no open transactions
END
END CATCH
Because you need to cater for various senarious:
A) an error that aborts the stored procedure
B) an error that closes the connection. (your client side code must
take over)
C) an error that will be caught by the Begin Try-End Try section.
What happens if you use dynamic SQL?
or am I just being an old chicken here, scared of ghosts and the like?
Best regards,
Henrik Staun Poulsen >> Stay informed about: Some questions about Stored Procedures, Error Handling,Tra.. |
|
| Back to top |
|
 |  |
External

Since: Aug 20, 2008 Posts: 672
|
(Msg. 8) Posted: Mon Dec 22, 2008 10:18 am
Post subject: Re: Some questions about Stored Procedures, Error Handling,Transactions... [Login to view extended thread Info.] Archived from groups: per prev. post (more info?)
|
|
|
Henrik,
It doesn't matter what code you put there. This is a general template
for error handling. Even if there is dynamic SQL, or stored procedure,
errors will be handled the same way. There is nothing you can do or
change if an error terminates the connection, and the client has to
handle that.
If you want to experiment, try placing in there the following calls:
SELECT 1/0;
EXEC('SELECT 1/0;');
EXEC Test;
Where stored procedure Test is defined as:
CREATE PROCEDURE Test
AS
SELECT 1/0;
--
Plamen Ratchev
http://www.SQLStudio.com >> Stay informed about: Some questions about Stored Procedures, Error Handling,Tra.. |
|
| Back to top |
|
 |  |
External

Since: Feb 11, 2008 Posts: 24
|
(Msg. 9) Posted: Tue Dec 23, 2008 3:48 am
Post subject: Re: Some questions about Stored Procedures, Error [Login to view extended thread Info.] Archived from groups: per prev. post (more info?)
|
|
|
Plamen,
Sorry, but I think I disagree:
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"
where
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'.
I'm really scared of those Begin Tran without Commit/Rollback. I've
been bitten badly, by missing Commit/rollbacks.
So I would prefer not to see any in my code.
But this is not possible. So I think that if we need to use "Begin
Tran", it should be neested into it own stored procedure somehow.
I'm just not sure how.
What do you think?
Best regards,
Henrik Staun Poulsen
www.stovi.com >> Stay informed about: Some questions about Stored Procedures, Error Handling,Tra.. |
|
| Back to top |
|
 |  |
External

Since: Aug 20, 2008 Posts: 672
|
(Msg. 10) Posted: Tue Dec 23, 2008 12:48 pm
Post subject: Re: Some questions about Stored Procedures, Error Handling,Transactions... [Login to view extended thread Info.] Archived from groups: per prev. post (more info?)
|
|
|
|
|
| Back to top |
|
 |  |
External

Since: May 30, 2004 Posts: 2060
|
(Msg. 11) Posted: Tue Dec 23, 2008 3:33 pm
Post subject: Re: Some questions about Stored Procedures, Error Handling,Transactions... [Login to view extended thread Info.] Archived from groups: per prev. post (more info?)
|
|
|
|
|
| Back to top |
|
 |  |
External

Since: Feb 11, 2008 Posts: 24
|
(Msg. 12) Posted: Mon Jan 19, 2009 4:45 am
Post subject: Re: Some questions about Stored Procedures, Error [Login to view extended thread Info.] Archived from groups: per prev. post (more info?)
|
|
|
Hi Plamen,
Sorry for the late reply, but better late than never...
<<I think the example you gave is not a reason for not using
transactions...
Well the example is just that; an example that shows one problem.
But it has also an idea for the solution; if we use a wrapper Sproc,
then we can catch more things.
So we have a MainSproc, and a HelperSproc.
The MainSproc what you suggest and if I'm really lucky some sort of
Auditing. Will I be so lucky?
The HelperSproc contains the application code, where a Begin Tran was
needed, but not the Begin Tran statements.
Your example lists this as " -- your code here "
I think this is a safer approach to transaction handlling. Do you
agree?
Best regards,
Henrik
On Dec 24 2008, 12:33 am, Erland Sommarskog
wrote:
> Henrik Staun Poulsen (h...@stovi.com) writes:
>
> > I'm really scared of those Begin Tran without Commit/Rollback. I've
> > been bitten badly, by missing Commit/rollbacks.
> > So I would prefer not to see any in my code.
>
> What? You don't want to see any BEGIN/COMMIT/ROLLBACK TRANSACTION in your
> code?
>
> > But this is not possible. So I think that if we need to use "Begin
> > Tran", it should be neested into it own stored procedure somehow.
> > I'm just not sure how.
> > What do you think?
>
> You should use transactions when you need them.
>
> And an error handler should always include a IF @@trancount > 0 ROLLBACK
> TRANSACTION, unless there are any other *known* requirements. This applies
> even if the stored procedure itself does not start a transaction.
>
> --
> Erland Sommarskog, SQL Server MVP, esq....DeleteThis@sommarskog.se
>
> Links for SQL Server Books Online:
> SQL 2008:http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
> SQL 2005:http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
> SQL 2000:http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx >> Stay informed about: Some questions about Stored Procedures, Error Handling,Tra.. |
|
| Back to top |
|
 |  |
External

Since: Jan 10, 2008 Posts: 640
|
(Msg. 13) Posted: Mon Jan 19, 2009 7:13 am
Post subject: Re: Some questions about Stored Procedures, Error [Login to view extended thread Info.] Archived from groups: per prev. post (more info?)
|
|
|
|
|
| Back to top |
|
 |  |
External

Since: Aug 20, 2008 Posts: 672
|
(Msg. 14) Posted: Mon Jan 19, 2009 8:24 am
Post subject: Re: Some questions about Stored Procedures, Error Handling,Transactions... [Login to view extended thread Info.] Archived from groups: per prev. post (more info?)
|
|
|
|
|
| Back to top |
|
 |  |
External

Since: Feb 11, 2008 Posts: 24
|
(Msg. 15) Posted: Tue Jan 20, 2009 2:39 am
Post subject: Re: Some questions about Stored Procedures, Error [Login to view extended thread Info.] Archived from groups: per prev. post (more info?)
|
|
|
Hi Plamen, Alex, Erland,
Sorry, but I should probably try to explain my problem better.
We have quite a few SSIS jobs for our Data Warehouse.
How can we add client side error handling to these?
How do you add some sort of auditing to a set of Begin Try, Begin
Transaction statements?
I think the best approach is to use a wrapper sproc, so that we catch
as many errors as possible.
Is this too much work, you think?
I would like to audit when some of our code ends up in an Begin Catch/
End Catch block.
Just a datetime, processid, (userid?), and some text, like procedure
name, maybe contents of variables.
Best regards,
Henrik >> Stay informed about: Some questions about Stored Procedures, Error Handling,Tra.. |
|
| Back to top |
|
 |  |
| Related Topics: | Libraries of Stored Procedures and Error Handling - I am trying to design a high quality set of library stored procedures in MSSQL 2005. My issue at hand is I don't know the best way to design error handling. For example, suppose I have the following stack of executed stored procedures in TSQ: Client..
Error handling questions - In my sprocs all SQL calls have TRY CATCH In CATCH, I want to log all error functions ERROR_MESSAGE(), ERROR_NUMBER() etc. etc. to a table. Can I call another sproc to do this or is the scope of the error functions only in the sproc where the error..
Questions about generated stored procedures by VS 2005 (Ta.. - Hi, When I let a TableAdapter generate stored procedure for "SELECT * FROM Supplier WHERE SupplierID = @SupplierID", it generates (some parts removed): Select: SET NOCOUNT ON; SELECT * FROM Supplier WHERE SupplierID = @SupplierID Update: SE...
OPENQUERY with stored procedures error - I am currently using SQL Server 2005 Express Edition and SSMSE. I have developed a unit testing suite for my stored procedures. The way it works is, all of my tests (stored procedures on the database that call the actual stored procedures to..
Exception handling in Stored procedure - Hi All, Conside this senario, (I am using SQL Server 2000) I have to process multiple orders and I have a store procedures to do this. This is schema/algorithm of my store proc Create Proc ProcessOrders Return ErrorStatus varchar(2000) Begin --.... |
|
You can post new topics in this forum You can reply to topics in this forum You can edit your posts in this forum You can delete your posts in this forum You can vote in polls in this forum
|
|
|
|
 |
|
|