Sunteți pe pagina 1din 5

Creating Custom Error Messages in SQL Server and using with VFP

SQL Server enables us to create and call our own error messages. We use these messages to keep our business logic traceable against violations. Both system and user defined error messages store by SQL server in the sysmessages table within master database.

Creating Custom Error Messages


We use sp_addmessage stored procedure to add custom error messages as following:

EXEC sp_addmessage @msgnum = number, @severity = severity_level, @msgtext = ' Text of error message.', @with_log = 'true' or 'false'
We need to have attention to the following points when we are going to create a custom message:

Custom message numbers can be considered from 50000 and higher Severity level is from 0 to 25 Only system administrators can create error messages with a severity level greater than 19 Use the @with_log option to control whether or not SQL Server records the error in the Windows Application log

Severity Levels: 0 through 10 These messages are considered informational (Info or Warnings normally I use 10 for this purpose). 11 through 16 These errors are correctable by the user. 17 This error shows insufficient resources (such as locks or disk space). 18 This error number is Non fatal internal error. These errors usually indicate an internal software problem. 19 This one is refer to an internal non-configurable limit in SQL Server which was exceeded. 20 through 25 These are fatal errors!!! Error messages with a severity greater than 20 will be considered as fatal with SQL Server and terminates the clients connection to the server. We can use 15 as the severity level for warning messages and 16 and higher as the severity level for errors.

Dropping Custom Error Messages


To remove a custom error message we use the sp_dropmessage stored procedure. The syntax is as following:

EXEC sp_dropmessage custom_message_number Replace custom_message_number with the number of the custom error message you want to delete from the sysmessages table. When an error is raised, the error number is placed in the @@ERROR function, which stores the most recently generated error number. The @@ERROR system function returns 0 if the last Transact-SQL statement executed successfully; if the statement generated an error, @@ERROR returns the error number. Also, @@ERROR is raised only for errors, not for warnings. @@ERROR is set to 0 by default for messages with a severity from 1 through 10.

Using Custom Error Messages


We can raise custom error messages by RAISEERROR which its syntax is as following: RAISERROR ( msg_id| msg_txt, severity_level, state) [WITH LOG] We will replace msg_id with the ID number of our created custom error message; remember that its stored in sysmessages table in master database. On the other hand we can optionally call RAISERROR to display a new message by specifying a message text which we need at that moment (We must also specify the severity level and state.) but we know that the instant message will not store by SQL Server to reuse. The state is an arbitrary number from 1 to 127 that you can use Its optionally to use the WITH LOG keywords with the RAISERROR statement to log the message in Windows Application log. To view these messages in Windows Application log we call Event Viewer from Administrative tools in control panel or by running it at %SystemRoot%\system32\eventvwr.msc /s. To have automatic logging of error message by SQL server we can set the @with_log option to true when we defined the custom error message by using the sp_addmessage stored procedure. Lets try a practical example: We write the codes in two parts, 1- First part would be through using SQL Query Analyzer to create custom error message and necessary store procedure. Defaults: *** To have a common sample, we use titles, and publishers tables in pubs database in Microsoft SQL server We want to delete a publisher if there is no any book title available in our titles table from that publisher. /* to check availability of error messages with number higher than 50000, we check sysmessage table in master database. */

Use master Select * from sysmessages where error > 50000 /* if we found any message in the above query result, we will go to drop them */ Exec sp_dropmessage 50001 Exec sp_dropmessage 50002 /* to add our error messages to SQL Server system message table we us sp_addmessage store procedure, because message texts are clearly describe the purpose of our error messages, I dont make more headache for you with extra explanations! */ Exec sp_addmessage @msgnum=50001, @severity=11, @msgtext='Publisher with name of %s is not available in Publishers table!', @with_log='true' Exec sp_addmessage @msgnum=50002, @severity=11, @msgtext='Not possible to delete %s because of availability of book(s) from this publisher in Titles table!', @with_log='true' Exec sp_addmessage @msgnum=50003, @severity=11, @msgtext='%s successfully deleted from Publishers table!', @with_log='true' /* to use pubs tables we switch there */ Use pubs /* to make a utility to delete a publisher with attention with its name, we create a store procedure. - First we check availability of name of the mentioned publisher in related table, if we dont have a publisher name in our table then we cant delete any one and we come up with an error message. - Second, now that we found the mentioned publisher ID, we will go to check between book titles to see if any of titles has been published with this publisher then we need to keep our integrity and we cant make it removed and just we alert it with a RAISERROR. - Finally we are ready to delete the publisher and we use an informative message for this purpose in Application log to make able for future traces. Note: @@ROWCOUNT function returns the number of rows affected by the last statement, @@ROWCOUNT is a system function. */ Create Procedure dbo.DeletePublisher @PublisherName varchar(40) = NULL

AS Declare @PublisherID char(4) Select @PublisherID = pub_id from publishers where pub_name = @PublisherName IF @@ROWCOUNT = 0 BEGIN Raiserror(50001, 11, 1, @PublisherName) RETURN END IF EXISTS (SELECT pub_id FROM titles WHERE pub_id = @PublisherID) BEGIN Raiserror (50002, 11, 1, @PublisherName) RETURN END DELETE FROM publishers WHERE pub_id = @PublisherID Raiserror (50003, 11, 1, @PublisherName) RETURN VFP PART: 2- Now to use the store procedure in Visual FoxPro we make a connection with SQL server, then we change current database to Pubs and finally call the function in SQL pass through method. Defaults: *** Please consider that the DSN in ODBC data source is FBSQL, use your own DSN to connect to your SQL server. lnSqlConn = SQLCONNECT("FBSQL")
&& we use pubs database:

SQLEXEC( lnSqlConn, "Use Pubs")


&& && && && && We need to add a new record to publishers table which dont have any reference in titles table to make us able to check deleting. We know pubs database, there is a constraint as relation between publishers and titles tables, it will not allow us to add a record in publishers then temporary we make it disable as following:

SqlExec(lnSqlConn, "alter table publishers nocheck constraint all")


&& Now we add a record for VFP Books publishing virtual publisher

SqlExec(lnSqlConn, "Insert into publishers values ( '1111', 'VFP Books Publishing', 'Richmond Hill', 'ON', 'Canada')")
&& Then we check the store procedure with 3 different publisher names && SqlExec command will bring -1 to show as error has been happened

SqlExec(lnSqlConn, "Exec dbo.DeletePublisher ' None exist publisher'") SqlExec(lnSqlConn, "Exec dbo.DeletePublisher ' New Moon Books'") SqlExec(lnSqlConn, "Exec dbo.DeletePublisher 'VFP Books Publishing'")
&& At last, we check our application log through Event Viewer && and we see the related error messages at there!

In real world we can use the custom message to log activities related to special happening by RAISERROR. In SQL Query Analyzer environment, when we encounter to RAISERROR, we can see the message in Messages tabs as an interactive message viewer part of the utility. Farhad Bayanati fbayanati@yahoo.com (from the VFUG Forum)

S-ar putea să vă placă și