473,883 Members | 1,412 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Error handling in stored procedure AND checking

I am stumped on the error reporting with sql server. I was told i
need to return @SQLCode(code showing if successful or not) and
@ErrMsg(and the message returned). I am clueless on this.

I wrote this procedure:

Expand|Select|Wrap|Line Numbers
  1. ALTER PROCEDURE [dbo].[usp_AcceptLeaveBalance]
  2.  
  3. @Emp_SSN int,
  4. @Annual_Forward decimal(10,2),
  5. @Sick_Forward decimal(10,2),
  6. @Family_Forward decimal(10,2),
  7. @Other_Forward decimal(10,2)
  8.  
  9. AS
  10.  
  11. UPDATE OT_MAIN
  12.  
  13. SET
  14.  
  15. EmpAnnual_Forward = IsNull(@Annual_Forward, EmpAnnual_Forward),
  16. EmpSick_Forward = IsNull(@Sick_Forward, EmpSick_Forward),
  17. EmpFamily_Forward = IsNull(@Family_Forward, EmpFamily_Forward),
  18. EmpOther_Forward = IsNull(@Other_Forward, EmpOther_Forward)
  19.  
  20. WHERE
  21.  
  22. Emp_SSN=@Emp_SSN
I can execute the procedure using this:

Expand|Select|Wrap|Line Numbers
  1. exec usp_AcceptLeaveBalance 123456789, 10, 10, null, 10
Sql comments that it is successful and that 0 rows are changed. I
know it shouldn't be successful because 123456789 does not refer to
any SSN.

So i am just inquring how to do the error handling and secondly I am
guessing I need to check to see if the ssn exists first.

Any suggestions or help.

I greatly appreciate it, and thanks for the help.
Jan 3 '08 #1
4 5083
SQL Server reports that the stored procedure executed successfully because
there are no errors. Just because your SQL statement attempts to update
non-existing SSN, it does not mean you will get an error. You have to handle
this using application logic, not to expect SQL Server to report an error.

If you really do want to get an error when invalid SSN update is attempted,
then you can add something like the code below at the end of your stored
procedure, just after the UPDATE statement:

IF @@ROWCOUNT = 0
RAISERROR ('Invalid SSN.', 16, 1)

The @@ROWCOUNT function returns the number of rows affected by the last
statement. Then if 0 rows have been updated it means the SSN is invalid and
RAISERROR will force an error.

However, based on the requirements that you need to return @SQLCode and
@ErrMsg, you are probably looking for something like this:

1). Add two OUTPUT parameters to the stored procedure for @@SQLCode and
@ErrMsg:
@SQLCode CHAR(1) OUTPUT, @ErrMsg VARCHAR(20) OUTPUT

2) Inside the stored procedure, just after the UPDATE check if rows have
been updated and set those two parameters:
IF @@ROWCOUNT = 0
SELECT @SQLCode = 'E', @ErrMsg = 'Invalid SSN.'

3) Then when you declare those two parameters and pass to the stored
procedure with the OUTPUT keyword.

This is just one example on how you can return the error code and message,
based on your application architecture different variations can be used. You
can probably go only with error message as the error code is redundant, but
not sure about your specs.

HTH,

Plamen Ratchev
http://www.SQLStudio.com

Jan 3 '08 #2
On Jan 3, 5:25*pm, "Plamen Ratchev" <Pla...@SQLStud io.comwrote:
SQL Server reports that the stored procedure executed successfully because
there are no errors. Just because your SQL statement attempts to update
non-existing SSN, it does not mean you will get an error. You have to handle
this using application logic, not to expect SQL Server to report an error.

If you really do want to get an error when invalid SSN update is attempted,
then you can add something like the code below at the end of your stored
procedure, just after the UPDATE statement:

IF @@ROWCOUNT = 0
RAISERROR ('Invalid SSN.', 16, 1)

The @@ROWCOUNT function returns the number of rows affected by the last
statement. Then if 0 rows have been updated it means the SSN is invalid and
RAISERROR will force an error.

However, based on the requirements that you need to return @SQLCode and
@ErrMsg, you are probably looking for something like this:

1). Add two OUTPUT parameters to the stored procedure for @@SQLCode and
@ErrMsg:
@SQLCode CHAR(1) OUTPUT, @ErrMsg VARCHAR(20) OUTPUT

2) Inside the stored procedure, just after the UPDATE check if rows have
been updated and set those two parameters:
IF @@ROWCOUNT = 0
SELECT @SQLCode = 'E', @ErrMsg = 'Invalid SSN.'

3) Then when you declare those two parameters and pass to the stored
procedure with the OUTPUT keyword.

This is just one example on how you can return the error code and message,
based on your application architecture different variations can be used. You
can probably go only with error message as the error code is redundant, but
not sure about your specs.

HTH,

Plamen Ratchevhttp://www.SQLStudio.c om
thanks for the help, i understand what and how you are doing it and
had the output variables in my stored procedure at one time, but the
if statement was my downfall. I showed the guy that told me to create
the procedure and said it was coming along but wanted me to setup if
there was an error(i am guessing any error) that he wants an email
generated with the error sent to him. I am at a complete standstill
till i figure that one out.

Thanks for the help I do appreciate it.
Jan 4 '08 #3
In general if I have an option I would prefer to handle e-mail notifications
at the application layer (that is the .NET application for example), where
this is much easier and more natural. In that case you just pass the output
parameters back to the application layer and use the utilities at hand to
send the e-mail notification.

Based on your notes seems that you need to send the e-mail notification from
inside the stored procedure. Here are a couple options:

1). If on SQL Server 2000 then you can use the built-in extended stored
procedure xp_sendmail. An example will be something like this:

EXEC master.dbo.xp_s endmail
@re************ ***@company.com ',
@message=N'Inva lid SSN.'

You can read more about all options and configuration for for xp_sendmail
here:
http://technet.microsoft.com/en-us/l.../ms189505.aspx

2). On SQL Server 2005 you can use sp_send_dbmail. Here is an example:

EXEC msdb.dbo.sp_sen d_dbmail
@profile_name = 'Test',
@recipients = 't***@company.c om',
@body = 'Invalid SSN.',
@subject = 'Automated notification'

More about sp_send_dbmail here:
http://msdn2.microsoft.com/en-us/library/ms190307.aspx

3). On SQL Server 2000 (and I have seen posts it works on SQL Server 2005
too) you can use the third party extended stored procedure xp_smtp_sendmai l.
It is using directly SMTP (while xp_sendmail uses MAPI), like sp_send_dbmail
does. More info about it here:
http://sqldev.net/xp/xpsmtp.htm

Note that all those methods for sending e-mail are not automatically
available. Read the information at the above links on security and
configuration.

HTH,

Plamen Ratchev
http://www.SQLStudio.com

Jan 5 '08 #4
On Jan 4, 10:30*pm, "Plamen Ratchev" <Pla...@SQLStud io.comwrote:
In general if I have an option I would prefer to handle e-mail notifications
at the application layer (that is the .NET application for example), where
this is much easier and more natural. In that case you just pass the output
parameters back to the application layer and use the utilities at hand to
send the e-mail notification.

Based on your notes seems that you need to send the e-mail notification from
inside the stored procedure. Here are a couple options:

1). If on SQL Server 2000 then you can use the built-in extended stored
procedure xp_sendmail. An example will be something like this:

EXEC master.dbo.xp_s endmail
* * * *@recipients=N' t...@company.co m',
* * * *@message=N'Inv alid SSN.'

You can read more about all options and configuration for for xp_sendmail
here:http://technet.microsoft.com/en-us/l.../ms189505.aspx

2). On SQL Server 2005 you can use sp_send_dbmail. Here is an example:

EXEC msdb.dbo.sp_sen d_dbmail
* * * *@profile_name = 'Test',
* * * *@recipients = 't...@company.c om',
* * * *@body = 'Invalid SSN.',
* * * *@subject = 'Automated notification'

More about sp_send_dbmail here:http://msdn2.microsoft.com/en-us/library/ms190307.aspx

3). On SQL Server 2000 (and I have seen posts it works on SQL Server 2005
too) you can use the third party extended stored procedure xp_smtp_sendmai l.
It is using directly SMTP (while xp_sendmail uses MAPI), like sp_send_dbmail
does. More info about it here:http://sqldev.net/xp/xpsmtp.htm

Note that all those methods for sending e-mail are not automatically
available. Read the information at the above links on security and
configuration.

HTH,

Plamen Ratchevhttp://www.SQLStudio.c om
Thanks for the help, I greatly appreciate it. I will look into the
link provided.
Jan 7 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
4781
by: Bill S. | last post by:
Hi, I a stored procedure that inserts a record into a table as below. The insert works OK, but if the insert violates a unique indewx constraint on one of the columns, the proc terminates immediately, and does NOT execute the 'if @@ERROR <> 0' statement.
1
2962
by: Jon LaRosa | last post by:
Hi all - I have a web application and I want to be able to do some basic error handling. For example, here is one error I would like to catch and display in a useful way for the user: ----------------- Microsoft OLE DB Provider for ODBC Drivers error '80040e14' UPDATE statement
9
10305
by: dtwilliams | last post by:
OK, i'm trying to do some error checking on stored procedures and am following the advise in Erland Sommarskog's 'Implementing Error Handling with Stored Procedures' document. Can anybody help with my stored procedures and why it keeps erroring at the '-- Create new Address Detail stage'? The errorCode value that is being return in my web app is 0, so i'm not even sure why it's even raising the error!! Rather than executing the INSERT...
0
4283
by: Rhino | last post by:
I've written several Java stored procedures now (DB2 V7.2) and I'd like to write down a few "best practices" for reference so that I will have them handy for future development. Would the experts here agree with the following? Would they add any other points? 1. If the shop standard calls for logging of application errors, a stored procedure should log any error that it encounters immediately upon detecting it and then return to the...
2
2912
by: Randy Harris | last post by:
I thought that I had a grasp of how VBA error handling functioned, but have just become painfully aware that I don't. I thought that the "On Error GoTo 0" in the second sub below would turn off error handling for that procedure. I single stepped the program, it gets an error on the last line (the Name Workdir... line), the next command to execute is Resume SkipReport. I know why the error occurs, but I don't understand how it resumes...
16
2660
by: Steve Jorgensen | last post by:
I'm trying to figure out if there is a way to generate standard error handlers that "know" if the calling code has an error handler in effect (On Error Goto <label> or On Error Resume Next) before deciding how to respond. Does anyone know if this is possible.
4
7622
by: James Radke | last post by:
Hello, I am looking for guidance on best practices to incorporate effective and complete error handling in an application written in VB.NET. If I have the following function in a class module (note that this class module represents the business layer of code NOT the gui layer): Public Function Test(ByVal Parm1 As Integer, ByVal Parm2 As Integer) As SqlDataReader ' Declare the SQL data layer class Dim oSQL As New...
1
2259
by: pob | last post by:
>From a form I have some code that calls 4 modules frmMain 1 mod 2 mod 3 mod 4 mod If mod 1 experiences an error the error handling works fine within mod 1 and writes out the error to a table, but the other modules still get
0
11622
by: Lysander | last post by:
Thought I would give something back with a few articles. This article is a bit of code to add error handling. When I have time, I want to write articles on multilingual databases, and Access Security, but I'll start with something short and simple This code was written in Access 2003 but should be valid in Access 2000 By default, when you start a new module, either in a form or report, or a global module, Access does not declare Option...
0
9933
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9789
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11129
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10838
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10408
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5794
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5988
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4213
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3230
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.