17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

As an example, let’s assume that AdventureWorks<strong>2008</strong> was implementing a rule that said that orders<br />

couldn’t be entered if they were more than seven days old. Knowing this rule, we could add our own<br />

custom message that tells the user about issues with their order date:<br />

sp_addmessage<br />

@msgnum = 60000,<br />

@severity = 10,<br />

@msgtext = ‘%s is not a valid Order date.<br />

Order date must be within 7 days of current date.’;<br />

Execute the sproc and it confirms the addition of the new message: Command(s) completed<br />

successfully.<br />

No matter what database you’re working with when you run sp_addmessage, the actual message is<br />

added to the master database and can be viewed at any time by looking at the sys.messages system<br />

view. The significance of this is that, if you migrate your database to a new server, the messages will<br />

need to be added again to that new server (the old ones will still be in the master database of the old<br />

server). As such, I strongly recommend keeping all your custom messages stored in a script somewhere<br />

so they can easily be added into a new system.<br />

Removing an Existing Custom Message<br />

To get rid of the custom message use:<br />

sp_dropmessage <br />

What a Sproc Offer s<br />

Now that we’ve spent some time looking at how to build a sproc, we probably ought to ask the question<br />

as to why to use them. Some of the reasons are pretty basic; others may not come to mind right away if<br />

you’re new to the RDBMS world. The primary benefits of sprocs include:<br />

❑ Making processes that require procedural action callable<br />

❑ Security<br />

❑ Performance<br />

Creating Callable Processes<br />

Chapter 12: Stored Procedures<br />

As I’ve already indicated, a sproc is something of a script that is stored in the database. The nice thing is<br />

that, because it is a database object, we can call to it — you don’t have to manually load it from a file<br />

before executing it.<br />

395

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!